Files
metal2vulkan/scripts/refusal-surface/refusal_surface.py
T
Anees Iqbal 5e3477e60a Translator: a buffer slot takes the storage view on every profile; the uniform view goes
A buffer slot took a uniform view only where containment was the device's
(contain::encoding gave Check::None, under robustBufferAccess or robustBufferAccess2): the
uniform arm of the slot's view choice and Profile F's per-stage storage-buffer fallback. The
runtime enables neither feature, so no runtime module took one. The next commit deletes the
robustness choice; memory, lower and spirv are crate-private, so its dead_code would fail that
commit on its own. The uniform view goes first, with everything that only it reached:

- the uniform forms of a view (UniformWords and UniformVec4) and their reads, and Profile F's
  fallback (fallback_view, fallback_rank). Profile F (runtime-floor without device addresses,
  below the runtime's floor) now refuses a stage past maxPerStageDescriptorStorageBuffers as
  DescriptorCount, where before it read its read-only slots through uniform views, under robust
  descriptors only;
- SlotPlan::lane_read and its planner pass, and Uniformity::among_active_lanes, which only that
  pass ran;
- the storage-view variant: LoweringInputs and VariantKey storage_view_slots, the binder's
  storage_view_variant and large_view_candidates;
- RuntimeFact::UniformViewAliasing and UniformViewRange with UniformViewChoice, and the binder's
  aliasing check with its refusal BindError::UniformViewAliased (docs/REFUSALS.md regenerated:
  binder refusals 9 to 8);
- SpecKey::RangeAtBindOffset (only uniform views declared it), BindState::view_base_alignment and
  uniform_views_at_residual, StageTable.at_bind_views and StageTable::class_alignment;
  BoundBuffer::shape, BoundBuffer::same_shape and StageTable::shape lose their
  view_base_alignment parameter;
- BufferRanges.uniform: BufferRanges::length_class and the binder's offset alignment now read
  maxStorageBufferRange and minStorageBufferOffsetAlignment alone. Nothing in the runtime crate
  reads BufferRanges, BindState, BoundBuffer, StageTable or BindShape (git grep: 0 hits); it
  reaches validation's candidate engine only;
- AccessClass::Uniform, DescriptorView (Storage, UniformWords, UniformVec4) and
  BufferForm::uniform_view; BufferForm::Descriptor loses its DescriptorView field.

The loop hoist stays: the argument table's Uniform block (lower::access::table, the spilled
push fields) still feeds it. Its docs no longer name a buffer slot's uniform view.

Removed or changed public items and the types that own them, each with 0 hits in the
consumer's checkout at bd9d6ae85a and at ad28ebd881 (git grep -w -F over *.rs, *.toml, *.md):
DescriptorView, UniformWords, UniformVec4,
UniformViewChoice, UniformViewRange, UniformViewAliasing, UniformViewAliased, RangeAtBindOffset,
storage_view_slots, view_base_alignment, uniform_views_at_residual, at_bind_views,
class_alignment, uniform_view, same_shape, AccessClass, BufferRanges, buffer_ranges, BufferForm,
StageTable, BoundBuffer, BindState, VariantKey, LoweringInputs, RuntimeFact, SpecKey, BindError.
crates/metal2vulkan/tests/api_signatures.tsv and api_surface.rs are blessed in this commit, and
docs/API.md (the uniform-view form, the bind-offset key, BufferRanges) changes with it.

Stored: VariantKey's storage_view_slots, and the codec tags of BufferForm::Descriptor (no
field), SpecKey (RangeAtBindOffset gone), RuntimeFact (two variants gone) and DescriptorView
(gone). The batch's ARTIFACT_FORMAT_VERSION bump (590 to 591), applied last once for the
batch, covers them; no version moves here.

Tests deleted whole, neither a containment proof: engine_storage_view_variant.rs (the
variant's fixed point) and engine_lane_reads.rs (the uniform view's lane choice). Deleted with
the forms they tested: the uniform-view cases of engine_access.rs and engine_binder.rs, the
slots tests of the large-view candidates and the bind-offset range, the variant's cache round
trip, and the active-lanes tests of lower/simd/uniform. The kept containment proof, a constant
buffer shorter than its window, runs on the storage form
(a_constant_buffer_shorter_than_its_window_is_contained_in_shader). Profile F's new refusal has
its test (a_stage_past_the_storage_buffer_limit_without_device_addresses_is_refused).

Golden: at the batch's top only the stated set's 24 texel-buffer rows moved, the 312 cells
commit 2 alone moved before the rebase; no other row moved on either set. The .air.ll half (567 typed-pointer fixtures,
which need metal-as) is unchecked per commit; the batch's golden bless on the M3 covers it.

Verified:
- On unshipped's tip before this rebase (96d953bb0b), the same change: compile job
  m3-max-66120 green (fmt, signatures, refusals, clippy plain, m2v_gpu and m2v_cpu_icd,
  workspace Rustdoc, api-docs). Before that rebase, this commit alone (hash probe job
  m3-max-65979) read 252 rows equal to its base's arm.
- At the batch's top on 96d953bb0b (all four commits, probe job m3-max-66130): the hash probe's
  252 rows equal unshipped's arm at 4861c9863d (m3-max-65976); the golden probe's set without
  buffer robustness (the runtime's state) equals the base arm 96d953bb0b (m3-max-66128), 1855 of
  1855 rows.
- The states-only play at the batch's top (render and compute states made and refused,
  pipelines_created, made_ahead_variants) is the coordinator's, run on the branch; it is not
  evidence here.
- Here: cargo fmt; signatures check; refusal surface regenerated. The compile job follows on the
  branch tip.
2026-11-22 00:17:41 -08:00

1218 lines
55 KiB
Python
Executable File

#!/usr/bin/env python3
"""Generate docs/REFUSALS.md: every refusal of something Metal accepts, from the code.
The refusal surface is read from the construction sites of the typed refusals, outside tests:
- the translator's and the AIR front end's `Unsupported` (a `Feature` and its `Needs`): the
constructors `Unsupported::not_implemented`, `not_representable`, `needs`, `needs_any_of`, and
`Unsupported { .. }`
literals, in the `src` of crates/metal2vulkan-air, crates/metal2vulkan and
crates/metal2vulkan-runtime;
- the binder's refusals of valid bind states at a device limit (`BindError`);
- the translation caps (`Limit`, `Error::LimitExceeded`);
- the rasterization-rate maps the compile layer does not compile (`UnpinnedCompile`);
- the translation deadline (`BudgetExceeded`, `Error::Budget`);
- the runtime's floor (`floor::BelowFloor`, in crates/metal2vulkan-runtime): each `floor::Missing`
item a device below the floor lacks;
- the runtime's own refusal enums: each variant of its `Error` whose payload is one enum it
declares (`Refused(Refusal)`, `Limit(Limit)`, and any added later), found from that payload, one
section each, every variant with a declared basis.
Each refusal is one row per variant, with what it blocks (the variant's doc comment), the device
condition (from the constructor: every device, or the capabilities, driver defects or families
its sites name), its sites, its basis, and a reach mark, which is the one hand-kept column
(`reach.tsv` beside this script).
The basis says where the belief that this input must be refused comes from. It is derived from the
construction site wherever the site states it, and declared in the refusal's own doc comment, as a
last line `Basis: <value> (the evidence)`, wherever the claim is about Metal itself, which no site
can state. `--check` requires one of every variant of the runtime's refusal enums: a refusal
that asserts Metal stops an input cannot be added with nothing behind it, and one whose basis is
not settled says `Basis: unknown (why)` rather than nothing. A translator refusal's is its `Needs`'
(`Needs::basis`'s arms), through the helper a site hands its feature to; `--check` fails on one
with a site that is not settled.
The same lines are the runtime's `basis()` of those enums, which it writes into `BASIS_RS`.
scripts/refusal-surface/refusal_surface.py # write docs/REFUSALS.md and basis.rs
scripts/refusal-surface/refusal_surface.py --check # fail when a variant, its
# condition, basis or reach mark is
# stale (the site lists may drift),
# or basis.rs is
scripts/refusal-surface/refusal_surface.py --table # print the plain table only
scripts/refusal-surface/refusal_surface.py --missing-basis # list refusals whose basis is
# absent or malformed
scripts/refusal-surface/refusal_surface.py --selftest # the basis marker's own cases
It reads source text only (no build), so it runs anywhere.
"""
import argparse
import re
import subprocess
import sys
from collections import Counter, OrderedDict, defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "docs" / "REFUSALS.md"
REACH = Path(__file__).resolve().parent / "reach.tsv"
CRATES = ROOT / "crates"
TREES = [
("air", CRATES / "metal2vulkan-air" / "src"),
("translator", CRATES / "metal2vulkan" / "src"),
("rt", CRATES / "metal2vulkan-runtime" / "src"),
]
# The runtime's floor: the file that declares `Missing`, the items of `BelowFloor`.
FLOOR_RS = CRATES / "metal2vulkan-runtime" / "src" / "floor.rs"
# The runtime's error: each variant whose payload is one enum the runtime declares is a family
# of typed refusals (`Refused(Refusal)`, `Limit(Limit)`, `Unsupported(Gap)`, and any added later).
RT_ERROR_RS = CRATES / "metal2vulkan-runtime" / "src" / "error.rs"
ERROR_RS = CRATES / "metal2vulkan" / "src" / "error" / "mod.rs"
BASIS_RS = CRATES / "metal2vulkan-runtime" / "src" / "error" / "basis.rs"
CONSTRUCTORS = {
"not_implemented": "NotImplemented",
"not_representable": "NotRepresentable",
"needs": "AnyOf",
"needs_any_of": "AnyOf",
}
# Binder refusals of a valid bind state: a device limit or an unestablished reading. The other
# `BindError` variants are Metal's own validation (misuse), or carry an `Unsupported` already
# counted under its feature.
BIND_REFUSALS = [
"DescriptorRangeExceeded",
"TexelBufferTooLarge",
"HeapTooLarge",
"TessellationFactorRange",
"PatchIndexRange",
"ControlPointIndexRange",
"MissingStageInRegion",
"MissingDeviceAddress",
]
REACH_MARKS = OrderedDict(
[
("system", "a guest's CoreAnimation, CoreImage or VideoToolbox plausibly reaches it"),
("app", "a typical Metal app plausibly reaches it from public API"),
("rare", "public API, but specialized: few apps reach it"),
("none", "no public API path: malformed or non-Metal input, Apple-private calls, or a cap no valid program of ordinary size meets"),
]
)
# The basis of a refusal: where the belief that this input must be refused comes from. One
# vocabulary for the whole surface.
#
# Where the construction site already says it, it is **derived** from the site and nothing is kept
# by hand: a capability a device lacks, a piece not built, a cap of this crate's. Where the claim
# is about Metal itself, no site can say it, so it is **declared** in the refusal's own doc comment
# as a last line, `Basis: <value> (the evidence)`, and `--check` requires one of every variant of
# `Problem` (section `invalid`), which is nothing but such claims.
BASIS = OrderedDict(
[
(
"metal-measured",
"Metal itself refuses the input, and a run of ours on a named device or release says so",
),
(
"metal-documented",
"Metal itself refuses it, and Apple's own words say so: a quoted assertion, `NSError` "
"or validation message, a header, or Apple's documentation",
),
(
"metal-takes",
"measured: plain Metal **takes** this input, so the refusal reaches past Metal. An open "
"defect, recorded here rather than left unsaid",
),
(
"device",
"the mechanism is absent: from this Vulkan device, from its driver, or from every "
"Vulkan device",
),
(
"ours",
"this crate's own gap, cap or deadline, or the misuse of a runtime extension Metal has "
"no counterpart for",
),
(
"unknown",
"not established: the refusal stands, and why Metal is believed to refuse this has not "
"been settled",
),
]
)
# A basis that claims something about Metal's own behaviour carries its evidence with it.
CITED_BASIS = ("metal-measured", "metal-documented", "metal-takes")
# A measurement names the device or the release it ran on.
NAMES_A_DEVICE = re.compile(r"\bM\d\b|\bApple M|\bmacOS\b|\b2[0-9]\.[0-9]")
# An aggregate variant carries no basis of its own: it forwards to another problem enum, whose
# variants hold the claims. `delegated(ThatEnum)` says so, and is held to the variant's payload.
DELEGATED = "delegated"
# A payload that is one problem enum: `Problem`'s forwarding variants carry nothing else, and the
# enum they name is read here too, so the claims inside it are held to a basis as the parent's are.
ONE_PROBLEM = re.compile(r"[A-Z][A-Za-z0-9_]*Problem")
def split_basis(doc):
"""(prose, marker): the doc without its trailing `Basis:` line, and that line's text.
The marker is the last thing in the doc comment, so one `rfind` finds it wherever the prose
above it goes; a `Basis:` left in the prose makes the tail unparsable, which `--check` reports
rather than passing over.
"""
i = doc.rfind("Basis:")
if i < 0:
return doc, None
return doc[:i].rstrip(), doc[i + len("Basis:") :].strip()
BASIS_MARKER = re.compile(r"([a-z][a-z-]*)\s*(?:\((.*)\))?\.?")
def parse_basis(marker, payload=""):
"""(value, citation, complaint) of one `Basis:` marker; `value` is None where it is malformed.
`payload` is the variant's payload type, which a `delegated` marker must name.
"""
m = BASIS_MARKER.fullmatch(marker.strip())
if not m:
return None, "", "is not `Basis: <value>` or `Basis: <value> (the evidence)`"
value, cite = m.group(1), (m.group(2) or "").strip()
if value == DELEGATED:
if not cite:
return None, "", "`delegated` names no enum: write `Basis: delegated(TheProblem)`"
if cite != payload.strip():
return None, "", f"`delegated({cite})` is not this variant's payload (`{payload.strip() or 'none'}`)"
return DELEGATED, cite, ""
if value not in BASIS:
return None, "", f"`{value}` is no basis: " + ", ".join(BASIS)
if value in CITED_BASIS and not cite:
return None, "", f"`{value}` claims something about Metal and cites no evidence"
if value in ("metal-measured", "metal-takes") and not NAMES_A_DEVICE.search(cite):
return None, "", f"`{value}` cites a run that names no device or release: `{cite}`"
return value, cite, ""
def kind_basis(text):
"""{`Needs` variant: basis}, from the arms of `Needs::basis` in `text` (lexed)."""
m = re.search(r"\bimpl\s+Needs\s*\{", text)
body = text[m.end() : close_of(text, m.end() - 1, "{", "}")] if m else ""
f = re.search(r"\bfn\s+basis\b", body)
out = {}
arm = r"((?:\s*\|?\s*Needs::\w+(?:\s*\([^)]*\))?)+)\s*=>\s*\{?\s*RefusalBasis::(\w+)"
for a in re.finditer(arm, body[f.end() :] if f else ""):
value = re.sub(r"(?<!^)(?=[A-Z])", "-", a.group(2)).lower()
for v in re.findall(r"Needs::(\w+)", a.group(1)):
out[v] = value
return out
# How each section's basis follows from the construction site, where it does. `None` is a section
# whose basis no site states: each variant's doc comment declares it. `table` is `kind_basis`'s.
def derived_basis(section, kinds, table):
if section == "feature":
bases = {table.get(k) for k in kinds}
if not kinds or None in bases:
return ""
# A site that refuses on every device because the lowering is not built settles the basis
# whatever the other sites need of a device.
if "ours" in bases:
return "ours"
return bases.pop() if len(bases) == 1 else ""
if section == "bind":
return "device"
# A cap, the deadline, and a rate map outside the bounds where Apple's compile was measured
# (`UnpinnedCompile`: "the bounds are this crate's, not Metal's").
if section in ("limit", "budget", "ratemap"):
return "ours"
if section == "floor":
return "device"
return ""
def lex(text):
"""Blank comments, strings and char literals (keeping newlines and offsets)."""
out = list(text)
i, n = 0, len(text)
def blank(a, b):
for k in range(a, b):
if out[k] != "\n":
out[k] = " "
while i < n:
c = text[i]
if text.startswith("//", i):
j = text.find("\n", i)
j = n if j < 0 else j
blank(i, j)
i = j
continue
if text.startswith("/*", i):
j = text.find("*/", i + 2)
j = n if j < 0 else j + 2
blank(i, j)
i = j
continue
if c == "r" and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")):
m = re.match(r'r(#*)"', text[i : i + 10])
if m:
close = '"' + m.group(1)
j = text.find(close, i + len(m.group(0)))
j = n if j < 0 else j + len(close)
blank(i + 1, j - 1)
i = j
continue
if c == '"':
j = i + 1
while j < n and text[j] != '"':
j += 2 if text[j] == "\\" else 1
blank(i + 1, j)
i = j + 1
continue
if c == "'":
m = re.match(r"'(\\.[^']*|[^'\\])'", text[i : i + 12])
if m:
blank(i + 1, i + len(m.group(0)) - 1)
i += len(m.group(0))
continue
i += 1
return "".join(out)
def close_of(text, start, open_ch, close_ch):
depth = 0
for k in range(start, len(text)):
if text[k] == open_ch:
depth += 1
elif text[k] == close_ch:
depth -= 1
if depth == 0:
return k
return len(text) - 1
def blank_test_items(text):
"""Blank `#[cfg(test)]` items (modules, functions, impls) so their sites do not count."""
out = list(text)
for m in re.finditer(r"#\[cfg\(test\)\]", text):
k = text.find("{", m.end())
semi = text.find(";", m.end())
if k < 0 or (0 <= semi < k):
continue
e = close_of(text, k, "{", "}")
for p in range(m.start(), e + 1):
if out[p] != "\n":
out[p] = " "
return "".join(out)
def source_files():
for tree, base in TREES:
for p in sorted(base.rglob("*.rs")):
rel = p.relative_to(ROOT).as_posix()
if "/tests/" in rel or rel.endswith("/tests.rs") or rel.endswith("_tests.rs"):
continue
yield tree, rel, blank_test_items(lex(p.read_text()))
def fn_spans(text):
"""(start, end, name) of every function body in text."""
spans = []
for m in re.finditer(r"\bfn\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:<[^{;]*?>)?\s*\(", text):
k = close_of(text, m.end() - 1, "(", ")")
b = text.find("{", k)
semi = text.find(";", k)
if b < 0 or (0 <= semi < b):
continue
name = m.group(1)
# A public `Device` method's body on the generation that serves is `<name>_now`, beside
# the method that forwards to it (`device/line.rs`): its sites are the method's.
if name.endswith("_now") and re.search(r"self\.current\(\)\s*\." + name + r"\(", text):
name = name[: -len("_now")]
spans.append((b, close_of(text, b, "{", "}"), name))
return spans
def enclosing(spans, pos):
best = None
for b, e, name in spans:
if b <= pos <= e and (best is None or b > best[0]):
best = (b, e, name)
return best
def line_of(text, pos):
return text.count("\n", 0, pos) + 1
def split_args(s):
args, depth, cur = [], 0, ""
for ch in s:
if ch in "([{<":
depth += 1
elif ch in ")]}>":
depth -= 1
if ch == "," and depth == 0:
args.append(cur.strip())
cur = ""
else:
cur += ch
if cur.strip():
args.append(cur.strip())
return args
CAP_TOKENS = r"(VkFeature|VkExtension|VkProperty|VkLimit|ApiVersion)::([A-Za-z0-9_]+)"
def conditions(kind, needs_text):
if kind == "NotImplemented":
return {"every device (not implemented)"}
if kind == "NotRepresentable":
return {"every device (no Vulkan mechanism)"}
toks = re.findall(CAP_TOKENS, needs_text)
if kind == "AnyOf":
caps = sorted({f"{a}::{b}" for a, b in toks if a.startswith("Vk") or a == "ApiVersion"})
if "Capability::Format" in needs_text or "FormatUsage::" in needs_text:
caps.append("a format's usage")
if not caps:
expr = " ".join(needs_text.split())
expr = re.sub(r"^vec!\[\s*(.*?)\s*\]$", r"\1", expr)
if "addressed_needs" in expr:
return {"devices without buffer device addresses (`addressed_needs`)"}
for cap, what in (("Limit", "a device limit"), ("Feature", "a Vulkan feature"), ("Property", "a Vulkan property"), ("Extension", "a Vulkan extension"), ("Format", "a format's usage")):
if expr.startswith(f"Capability::{cap}"):
return {f"devices short of {what} the site names"}
if expr and len(expr) <= 70:
return {f"devices without a capability the site computes (`{expr}`)"}
return {"devices without a capability the site computes"}
return {"devices without " + c for c in caps}
return {"varies (" + kind + ")"}
def is_pattern(text, start, end):
"""Whether the variant path at [start, end) is a match pattern rather than a value."""
k = end
while k < len(text) and text[k] in " \t":
k += 1
if k < len(text) and text[k] in "({":
k = close_of(text, k, text[k], ")" if text[k] == "(" else "}") + 1
rest = text[k : k + 3].lstrip()
if rest.startswith("=>") or (rest.startswith("|") and not rest.startswith("||")):
return True
before = text[max(0, start - 30) : start].rstrip()
# A closure's parameters (`let refuse = |a, b| Variant { .. }`) end in `|` too: the value
# after them is built, not matched.
closure = re.search(r"(?:=|\(|,|\bmove)\s*\|[^|]*\|$", text[max(0, start - 80) : start].rstrip())
if before.endswith("|") and not before.endswith("||") and not closure:
return True
if re.search(r"\b(let|matches!\([^,]*,)\s*$", text[max(0, start - 60) : start]):
return True
if before.endswith("let") or before.endswith("Some(") and "let" in text[max(0, start - 40) : start]:
return True
return False
# The front end's `Feature` converted to the translator's (`error/mod.rs`): a reference there is
# the front end's refusal.
FRONT_END_FROM = re.compile(r"impl\s+From<\s*crate::air::error::Feature\s*>\s+for\s+Feature\s*\{")
def callee(text, pos):
"""The function whose call's parentheses hold `pos`, innermost first, or None outside a call."""
depth = 0
for k in range(pos - 1, -1, -1):
c = text[k]
if c in ")]}":
depth += 1
elif c in "([{" and depth:
depth -= 1
elif c == "(":
m = re.search(r"([A-Za-z_][A-Za-z0-9_]*)\s*$", text[:k])
return m.group(1) if m else None
elif c in "{;":
return None
return None
def follow(files, helpers, by_name, rel, pos, depth=0):
"""The (kind, condition) pairs of the refusals a feature reference at `pos` of `rel` reaches,
or None: the front end's (it refuses only what it does not implement), a construction's whose
feature argument it is, a helper's it is handed to, its function's, or, in a function that
returns the feature, those its calls in the file reach.
"""
tree, text, spans, ctors, computed, front = files[rel]
if tree == "air" or any(b <= pos <= e for b, e in front):
return {("NotImplemented", c) for c in conditions("NotImplemented", "")}
for b, e, kind, conds in ctors:
if b <= pos <= e:
return {(kind, c) for c in conds}
name = callee(text, pos)
homes = [rel] if (rel, name) in helpers else sorted(by_name.get(name, ()))
if len(homes) == 1:
return helpers[(homes[0], name)]
enc = enclosing(spans, pos)
if enc is None:
return None
built = {(k, c) for p, k, conds in computed if enc[0] <= p <= enc[1] for c in conds}
if built:
return built
calls = [m.start() for m in re.finditer(r"(?<![\w.])" + enc[2] + r"\s*\(", text)]
calls = [c for c in calls if not re.search(r"\bfn\s+$", text[max(0, c - 8) : c])]
if depth >= 4 or not calls:
return None
out = set()
for c in calls:
got = follow(files, helpers, by_name, rel, c, depth + 1)
if got is None:
return None
out |= got
return out
def scan(rt_enums=()):
"""Rows keyed by (section, variant): conditions, sites.
`rt_enums` are the runtime's refusal enums ([`rt_refusal_enums`]), each its own section.
"""
rows = defaultdict(lambda: {"conds": set(), "kinds": set(), "sites": [], "indirect": []})
feature_refs, ref_pos, files = defaultdict(list), defaultdict(list), {}
for tree, rel, text in source_files():
spans = fn_spans(text)
# For `follow`: each construction, those of a computed feature, the front end's `From`.
ctors, computed = [], []
front = [(m.end() - 1, close_of(text, m.end() - 1, "{", "}")) for m in FRONT_END_FROM.finditer(text)]
files[rel] = (tree, text, spans, ctors, computed, front)
def site(pos):
"""A construction site: its file, its line, and the function that builds the refusal.
The line is carried only so two matches of one construction count as one site; `cite`
does not print it.
"""
enc = enclosing(spans, pos)
return (rel, line_of(text, pos), enc[2] if enc else "")
# Unsupported constructors.
for m in re.finditer(r"\bUnsupported::(" + "|".join(CONSTRUCTORS) + r")\s*\(", text):
k = m.end() - 1
e = close_of(text, k, "(", ")")
args = split_args(text[k + 1 : e])
kind = CONSTRUCTORS[m.group(1)]
feat = args[0] if args else ""
fm = re.match(r"(?:\w+::)*Feature::([A-Za-z0-9_]+)", feat)
name = fm.group(1) if fm else None
needs_text = " ".join(args[1:])
if name is None:
key = ("feature", "(computed)")
else:
key = ("feature", name)
rows[key]["conds"] |= conditions(kind, needs_text)
rows[key]["kinds"].add(kind)
rows[key]["sites"].append(site(m.start()))
ctors.append((k, e, kind, conditions(kind, needs_text)))
if name is None:
computed.append((m.start(), kind, conditions(kind, needs_text)))
# Unsupported { feature: .., needs: .. } literals.
for m in re.finditer(r"\bUnsupported\s*\{", text):
pre = text[max(0, m.start() - 12) : m.start()]
if "struct" in pre or "enum" in pre:
continue
e = close_of(text, m.end() - 1, "{", "}")
body = text[m.end() : e]
fm = re.search(r"\bfeature\s*:\s*(?:\w+::)*Feature::([A-Za-z0-9_]+)", body)
nm = re.search(r"\bneeds\s*:\s*(?:\w+::)*Needs::([A-Za-z0-9_]+)", body)
if not re.search(r"\bfeature\s*:", body):
continue # a pattern (`Unsupported { feature, .. }`)
if is_pattern(text, m.start(), e + 1):
continue
name = fm.group(1) if fm else "(computed)"
kind = nm.group(1) if nm else "computed"
needs_text = body[nm.start() :] if nm else ""
rows[("feature", name)]["conds"] |= conditions(kind, needs_text)
rows[("feature", name)]["kinds"].add(kind)
rows[("feature", name)]["sites"].append(site(m.start()))
ctors.append((m.end() - 1, e, kind, conditions(kind, needs_text)))
if fm is None:
computed.append((m.start(), kind, conditions(kind, needs_text)))
# Indirect feature references (a feature handed to a helper that builds the refusal).
for m in re.finditer(r"\bFeature::([A-Za-z0-9_]+)", text):
if is_pattern(text, m.start(), m.end()):
continue
feature_refs[m.group(1)].append(site(m.start()))
ref_pos[m.group(1)].append((rel, m.start()))
if tree == "rt":
# `Missing`: an item of the floor a device lacks, built where the floor decides.
for m in re.finditer(r"(?<![A-Za-z0-9_])Missing::([A-Z][A-Za-z0-9_]*)", text):
if is_pattern(text, m.start(), m.end()):
continue
rows[("floor", m.group(1))]["sites"].append(site(m.start()))
# The runtime's own refusal enums, one section each.
for enum in rt_enums:
for m in re.finditer(r"(?<![A-Za-z0-9_])" + enum + r"::([A-Z][A-Za-z0-9_]*)", text):
if is_pattern(text, m.start(), m.end()):
continue
rows[(rt_section(enum), m.group(1))]["sites"].append(site(m.start()))
for m in re.finditer(r"\bBindError::([A-Z][A-Za-z0-9_]*)", text):
if m.group(1) not in BIND_REFUSALS or is_pattern(text, m.start(), m.end()):
continue
rows[("bind", m.group(1))]["sites"].append(site(m.start()))
for m in re.finditer(r"\bLimit::([A-Z][A-Za-z0-9_]*)", text):
if tree == "rt" or is_pattern(text, m.start(), m.end()):
continue
if rel.endswith("metal2vulkan-air/src/error.rs"):
continue
rows[("limit", m.group(1))]["sites"].append(site(m.start()))
for enum, section in (("UnpinnedCompile", "ratemap"), ("BudgetExceeded", "budget")):
for m in re.finditer(r"\b" + enum + r"::([A-Z][A-Za-z0-9_]*)", text):
if is_pattern(text, m.start(), m.end()):
continue
rows[(section, m.group(1))]["sites"].append(site(m.start()))
# A helper: a function that builds a refusal of a computed feature, by file and by name.
helpers, by_name = defaultdict(set), defaultdict(set)
for rel, (_, _, spans, _, computed, _) in files.items():
for pos, kind, conds in computed:
enc = enclosing(spans, pos)
if enc:
helpers[(rel, enc[2])] |= {(kind, c) for c in conds}
by_name[enc[2]].add(rel)
followed = {n: [follow(files, helpers, by_name, rel, pos) for rel, pos in refs] for n, refs in ref_pos.items()}
return rows, feature_refs, followed
def enum_arms(path, enum):
"""(variant, doc, payload, pattern) of `pub enum <enum>` in path, in order; the pattern
matches the variant whatever it holds (`Name`, `Name(..)` or `Name { .. }`).
Struct variants are stepped over by brace depth, so a field's own doc comment is never read as
the next variant's. This is the reader for `Problem` and for every problem enum it forwards to:
those are the refusals whose basis is declared, and a doc comment read wrongly would lose one.
"""
lines = path.read_text().split("\n")
out, doc, inside, depth = [], [], False, 0
for line in lines:
if not inside:
if re.match(r"pub enum " + enum + r" \{", line):
inside = True
continue
if depth == 0 and line.startswith("}"):
break
if depth:
depth += line.count("{") - line.count("}")
continue
s = line.strip()
if s.startswith("///"):
doc.append(s[3:].strip())
continue
m = re.match(r"^ ([A-Z][A-Za-z0-9_]*)\s*(\(|\{|,)", line)
if m:
payload = ""
if m.group(2) == "(" and ")" in line:
payload = line[line.index("(") + 1 : line.rindex(")")]
elif m.group(2) == "{":
depth = 1
pattern = m.group(1) + {"(": "(..)", "{": " { .. }", ",": ""}[m.group(2)]
out.append((m.group(1), " ".join(doc), payload, pattern))
doc = []
elif s and not s.startswith("//") and not s.startswith("#"):
doc = []
return out
def enum_variants(path, enum):
"""(variant, doc) of `pub enum <enum>` in path, in order."""
lines = path.read_text().split("\n")
out, doc, inside = [], [], False
for line in lines:
if not inside:
if re.match(r"pub enum " + enum + r"\b", line):
inside = True
continue
if line.startswith("}"):
break
s = line.strip()
if s.startswith("///"):
doc.append(s[3:].strip())
continue
m = re.match(r"^ ([A-Z][A-Za-z0-9_]*)\b", line)
if m:
out.append((m.group(1), " ".join(doc)))
if s and not s.startswith("//") and not s.startswith("#"):
doc = []
return out
def rt_section(enum):
"""The section key of one of the runtime's refusal enums."""
return f"rt:{enum}"
def rt_refusal_enums():
"""(variant, enum, file) for each variant of the runtime's `Error` whose whole payload is
one enum the runtime declares: `Refused(Refusal)`, `Limit(Limit)`, and any family added later.
Structural: no list of names is kept here.
"""
where = {}
for tree, rel, text in source_files():
if tree != "rt":
continue
for m in re.finditer(r"^pub enum ([A-Za-z0-9_]+) \{", text, re.M):
where.setdefault(m.group(1), ROOT / rel)
out = []
for name, _, payload, _ in enum_arms(RT_ERROR_RS, "Error"):
payload = payload.strip()
if re.fullmatch(r"[A-Z][A-Za-z0-9_]*", payload) and payload in where and payload != "Error":
out.append((name, payload, where[payload]))
return out
def basis_rs(enums, values):
"""(text, faults): each `(enum, enum_arms)`'s `basis()`, an arm per variant from its `Basis:`
line, as `cargo fmt` leaves it; `values` are the variants of `RefusalBasis`."""
names = ", ".join(sorted([enum for enum, _ in enums] + ["RefusalBasis"]))
out = [
"// Generated by scripts/refusal-surface/refusal_surface.py from the `Basis:` line that ends",
"// each variant's doc comment. Never edit it by hand: change the doc comment and regenerate.",
"",
f"use crate::{{{names}}};",
]
faults = []
for enum, arms in enums:
out += ["", f"impl {enum} {{", " /// The variant's `Basis:` line, as [`Error::basis`](crate::Error::basis) answers it. Metal"]
out += [" /// has no counterpart.", " pub fn basis(self) -> RefusalBasis {", " match self {"]
for name, doc, payload, pattern in arms:
marker = split_basis(doc)[1] or ""
variant = "".join(w.capitalize() for w in (parse_basis(marker, payload)[0] or "").split("-"))
arm = f" {enum}::{pattern} => "
if variant not in values:
faults.append(f"{enum}::{name}: `Basis: {marker}` names no variant of `RefusalBasis`")
elif len(arm) + len(variant) <= 85:
out.append(f"{arm}RefusalBasis::{variant},")
elif len(arm) <= 95: # rustfmt's block form, which past this breaks the pattern too
out.append(f"{arm}{{\n RefusalBasis::{variant}\n }}")
else:
faults.append(f"{enum}::{name}: a name too long for its arm's pattern to keep one line")
out += [" }", " }", "}"]
return "\n".join(out) + "\n", faults
# A citation of the design record, a work package or an open item, which a reader of this
# file cannot follow: dropped from the summaries.
REF = r"(?:refining |DESIGN )?D\d+(?:\.\d+)?(?: (?:items?|part) \d+(?:(?:, | and )\d+)*)?|WP-[A-Z0-9]+[a-z]?|U\d+"
def strip_refs(text):
text = re.sub(rf"\s*\((?:{REF})(?:[,;] (?:{REF}))*\)", "", text)
text = re.sub(rf"[,;] (?:{REF})(?=[,;)])", "", text)
return re.sub(rf"\((?:{REF})[,;] ", "(", text)
def summary(doc):
# A rustdoc link `[text](path)` reads as its text: the path is the crate's, not this file's.
doc = re.sub(r"\[([^\]]+)\]\([^)\s]*\)", r"\1", strip_refs(doc.strip()))
if not doc:
return ""
m = re.match(r"(.+?[.:])(\s|$)", doc)
first = m.group(1) if m else doc
first = first.rstrip(":").rstrip(".")
if len(first) > 150:
first = first[:147].rsplit(" ", 1)[0] + "..."
return first.replace("|", "\\|")
def load_reach():
reach = {}
if REACH.exists():
for line in REACH.read_text().split("\n"):
if not line.strip() or line.startswith("#"):
continue
f = line.split("\t")
while len(f) < 4:
f.append("")
reach[(f[0], f[1])] = (f[2], f[3])
return reach
def cite(sites):
"""The sites of one refusal as `file (function)`, in file order, deduplicated.
No line number: it is right for one state of the tree only, while the function is right in
every tree that has it and is what a reader searches for. Where one function builds more than
one site the count says so, so dropping the line loses no site.
"""
counted = Counter((rel, fn) for rel, _, fn in set(sites))
out = []
for (rel, fn), n in sorted(counted.items()):
inside = ", ".join(x for x in (fn, f"{n} sites" if n > 1 else "") if x)
out.append(f"{rel} ({inside})" if inside else rel)
return out
def sites_cell(sites):
"""How many construction sites, then the first two as `file (function)`."""
if not sites:
return "0"
first = cite(sites)
shown = ", ".join(f"`{s}`" for s in first[:2])
more = f" (+{len(first) - 2})" if len(first) > 2 else ""
return f"{len(set(sites))}: {shown}{more}"
def head_sha():
"""HEAD's short sha, for the `--table` print. A tracked file carries no such stamp: it would
differ on every regeneration without a refusal having changed."""
try:
return subprocess.check_output(["git", "-C", str(ROOT), "rev-parse", "--short=9", "HEAD"], text=True).strip()
except Exception:
return "unknown"
def build(rt_enums):
rows, feature_refs, followed = scan([enum for _, enum, _ in rt_enums])
table = kind_basis(lex(ERROR_RS.read_text()))
reach = load_reach()
fdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan" / "src" / "error" / "mod.rs", "Feature"))
for n, d in enum_variants(CRATES / "metal2vulkan-air" / "src" / "error.rs", "Feature"):
fdocs.setdefault(n, d)
bdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan" / "src" / "error" / "mod.rs", "BindError"))
ldocs = OrderedDict(enum_variants(CRATES / "metal2vulkan-air" / "src" / "error.rs", "Limit"))
rdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan" / "src" / "bind" / "rate_map.rs", "UnpinnedCompile"))
tdocs = OrderedDict(enum_variants(CRATES / "metal2vulkan-air" / "src" / "error.rs", "BudgetExceeded"))
mdocs = OrderedDict(enum_variants(FLOOR_RS, "Missing"))
for n, refs in feature_refs.items():
if n in fdocs and not rows[("feature", n)]["sites"]:
rows[("feature", n)]["indirect"] = refs
# Settled only where every reference reaches a refusal: one it cannot follow could
# be of any `Needs`.
if all(f is not None for f in followed[n]):
for f in followed[n]:
rows[("feature", n)]["kinds"] |= {k for k, _ in f}
rows[("feature", n)]["conds"] |= {c for _, c in f}
tables = OrderedDict()
missing_reach = []
basis_faults = []
sections = [
("feature", fdocs, "Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`)"),
("bind", OrderedDict((n, bdocs.get(n, "")) for n in BIND_REFUSALS), "Binder refusals at a device limit (`BindError`)"),
("limit", ldocs, "Translation caps (`Error::LimitExceeded(Limit)`)"),
(
"ratemap",
rdocs,
"Rate maps the compile layer does not compile (`UnpinnedCompile`)",
),
("budget", tdocs, "The translation deadline (`Error::Budget`)"),
("floor", mdocs, "Devices below the runtime's floor (`floor::BelowFloor`: each `floor::Missing`)"),
]
for variant, enum, file in rt_enums:
sections.append(
(
rt_section(enum),
OrderedDict((n, d) for n, d, _, _ in enum_arms(file, enum)),
f"The runtime's `{enum}` (`Error::{variant}({enum})`)",
)
)
for section, docs, title in sections:
out = []
for name, doc in docs.items():
r = rows.get((section, name))
sites = (r["sites"] if r else [])
indirect = (r["indirect"] if r else [])
conds = sorted(r["conds"]) if r else []
if section in ("bind", "limit"):
conds = ["at the device's limit" if section == "bind" else "every device (a deterministic cap)"]
elif section == "ratemap":
conds = ["every device (this crate's bound: Apple's compile unmeasured or crashing there)"]
elif section == "budget":
conds = ["every device (the attempt's deadline, 20 seconds by default)"]
elif section == "floor":
conds = ["devices below the floor, at device creation"]
if not sites and not indirect:
state = "no site"
elif not sites and indirect:
state = "indirect"
else:
state = "direct"
notsched = " (not scheduled)" if "not scheduled" in doc.lower() else ""
if section == "floor" or section.startswith("rt:"):
# Reach is not marked here: every one of these is an argument of a public call,
# so a reach mark would say `app` for all of them; and the floor turns on the
# device, whatever the program.
rm = ("-", "")
else:
rm = reach.get((section, name))
if rm is None:
missing_reach.append((section, name))
rm = ("?", "")
prose, marker = split_basis(doc)
if marker is None:
basis, cite = derived_basis(section, (r["kinds"] if r else set()), table), ""
if section.startswith("rt:"):
basis_faults.append((section, name, "carries no `Basis:` line"))
else:
basis, cite, complaint = parse_basis(marker)
if basis is None:
basis_faults.append((section, name, complaint))
basis = ""
doc = prose
if section.startswith("rt:"):
# A device's own limit refuses on devices whose limit the call passes; every other
# refusal of the runtime is a public call's check of its arguments.
if basis == "device":
conds = ["at the device's limit"]
else:
conds = ["every device (a public call's own check of its arguments)"]
if sites:
sc = sites_cell(sites)
elif indirect:
sc = "via a helper: " + sites_cell(indirect)
else:
sc = "0"
out.append(
{
"name": name,
"what": summary(doc) + notsched,
"cond": "; ".join(conds) if conds else "-",
"sites": sc,
"state": state,
"reach": rm[0],
"why": rm[1].replace("|", "\\|"),
"basis": basis or "-",
"cite": cite.replace("|", "\\|"),
"size": "",
"all": sorted(set(sites or indirect)),
}
)
tables[section] = (title, out)
return tables, missing_reach, basis_faults
def render(tables):
lines = []
lines.append("# The refusal surface")
lines.append("")
lines.append(
"Every refusal of something Metal accepts, read from the code: the construction sites of the "
"typed refusals outside tests (`scripts/refusal-surface/refusal_surface.py`, which writes this "
"file; edit its `reach.tsv` and the refusals' own doc comments, never the tables). "
"Section 6 is the runtime's floor: a "
"device below it is refused when the device is made, with every item it lacks named. "
"The sections after it are the runtime's own typed refusals, one for each enum its "
"`Error` carries, every row with its declared basis, which the runtime answers at run time "
"too, by `Error::basis`. "
"Malformed input of no Metal call at all is misuse and is not listed. "
"[`METAL-COVERAGE.md`](METAL-COVERAGE.md) lists the Metal API the runtime has no "
"counterpart for at all."
)
lines.append("")
lines.append("Columns:")
lines.append("")
lines.append(
"- **What it blocks**: the variant's doc comment, first sentence, and \"not scheduled\" "
"where the doc says so."
)
lines.append(
"- **Where**: the device condition, from the constructor at its sites: `NotImplemented` and "
"`NotRepresentable` refuse on every device; `needs` names the Vulkan feature, extension, "
"property or limit a device lacks; a driver defect or deviation names the driver. A site that "
"computes its capability says so."
)
lines.append(
"- **Sites**: how many construction sites, then the first two as `file (function)`, with "
"the count where one function builds more than one. \"via a helper\" counts the places "
"that hand the feature to a function that builds the refusal; 0 is a variant nothing builds "
"today."
)
lines.append(
"- **Basis**: where the belief that this input must be refused comes from. Derived from the "
"construction site where the site says it (`device`, `ours`; a translator refusal's from its "
"`Needs`, as `Needs::basis` answers it, through the helper a site hands its feature to, and "
"`ours` where any site is not implemented), declared as a last `Basis:` "
"line in the refusal's own doc comment where the claim is about Metal itself, and `-` where "
"neither says it yet:"
)
for k, v in BASIS.items():
lines.append(f" - `{k}`: {v};")
lines.append("- **Reach** (hand-kept, `reach.tsv`):")
for k, v in REACH_MARKS.items():
lines.append(f" - `{k}`: {v};")
lines.append(" - `?`: not assessed yet.")
lines.append(
" The floor (section 6) carries no reach mark, as it turns on the device whatever the "
"program, and nor do the runtime's refusals after it, each an argument of a public "
"call."
)
lines.append("")
# totals
lines.append("## Totals")
lines.append("")
lines.append("| Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed |")
lines.append("|---|---|---|---|---|---|---|---|")
for section, (title, rows) in tables.items():
c = defaultdict(int)
for r in rows:
c[r["reach"]] += 1
live = sum(1 for r in rows if r["state"] != "no site")
lines.append(
f"| {title.split(' (')[0]} | {len(rows)} | {live} | {c['system']} | {c['app']} | {c['rare']} | {c['none']} | {c['?']} |"
)
lines.append("")
lines.append("## Totals by basis")
lines.append("")
cols = list(BASIS) + ["delegated", "-"]
lines.append("| Kind | " + " | ".join(f"`{k}`" for k in cols) + " |")
lines.append("|---" * (len(cols) + 1) + "|")
for section, (title, rows) in tables.items():
c = defaultdict(int)
for r in rows:
c[r["basis"]] += 1
lines.append(f"| {title.split(' (')[0]} | " + " | ".join(str(c[k]) for k in cols) + " |")
lines.append("")
for i, (section, (title, rows)) in enumerate(tables.items(), 1):
lines.append(f"## {i}. {title}")
lines.append("")
lines.append("| Variant | What it blocks | Where | Basis | Sites | Reach |")
lines.append("|---|---|---|---|---|---|")
for r in rows:
reach = f"`{r['reach']}`" + (f": {r['why']}" if r["why"] else "")
basis = f"`{r['basis']}`" + (f": {r['cite']}" if r["cite"] else "")
lines.append(
f"| `{r['name']}` | {r['what']} | {r['cond']} | {basis} | {r['sites']} | {reach} |"
)
lines.append("")
lines.append("## Appendix: every site")
lines.append("")
lines.append("Each refusal's sites, with the function that builds it.")
lines.append("")
for section, (title, rows) in tables.items():
for r in rows:
if not r["all"]:
continue
lines.append(f"- `{section}::{r['name']}`: " + "; ".join(f"`{x}`" for x in cite(r["all"])))
lines.append("")
return "\n".join(lines) + "\n"
def plain_table(tables):
"""One Markdown table of every refusal, most reachable first, with short device conditions."""
order = {k: i for i, k in enumerate(REACH_MARKS)}
def short(c):
parts = []
for p in c.split("; "):
p = p.replace("devices without one of ", "lacking one of ").replace("devices without ", "lacking ")
p = p.replace("every device (not implemented)", "all devices: not built")
p = p.replace("every device (no Vulkan mechanism)", "all devices: no Vulkan form")
p = re.sub(r"Vk(Feature|Extension|Limit|Property)::", "", p)
parts.append(p)
# Every device's refusal (not built, no Vulkan form) first, so a long list of device
# conditions never cuts it off.
parts.sort(key=lambda p: not p.startswith("all devices"))
s = "; ".join(parts)
return s if len(s) < 160 else s[:157] + "..."
rows = [(order.get(x["reach"], len(order)), sec, x) for sec, (_, rs) in tables.items() for x in rs]
rows.sort(key=lambda t: (t[0], t[1], t[2]["name"]))
out = [
f"# The refusal surface at `{head_sha()}`",
"",
"Reach: " + "; ".join(f"{k} = {v}" for k, v in REACH_MARKS.items()) + ".",
"",
"Basis: " + "; ".join(f"{k} = {v}" for k, v in BASIS.items()) + ".",
"",
"| Reach | Basis | Kind | Refusal | Blocks | Where | Sites |",
"|---|---|---|---|---|---|---|",
]
for _, sec, x in rows:
n = x["sites"].split(" ")[0].rstrip(":")
if x["sites"].startswith("via"):
n = "via a helper"
what = x["what"] if len(x["what"]) < 110 else x["what"][:107] + "..."
out.append(f"| {x['reach']} | {x['basis']} | {sec} | {x['name']} | {what} | {short(x['cond'])} | {n} |")
return "\n".join(out) + "\n"
def selftest():
"""The basis marker's parse, over markers written here, both ways.
The column is worth no more than this parse: a marker shape it stops recognising takes a claim
out of the table, and a smaller table then reads like the truth. So each case asserts both that
a good marker is read as what it says and that a bad one is named, and `--check` cannot pass a
tree whose refusal enums carry no marker at all.
"""
good = [
("metal-measured (an Apple M3 Max, macOS 27.0.1: the call asserts)", "", "metal-measured"),
("metal-documented (Metal asserts \"commit an already committed command buffer\")", "", "metal-documented"),
("metal-takes (an M3 Max: plain Metal returns and the pass completes)", "", "metal-takes"),
("device", "", "device"),
("ours", "", "ours"),
("unknown (Metal's answer here is unmeasured)", "", "unknown"),
("unknown", "", "unknown"),
("delegated(TextureProblem)", "TextureProblem", "delegated"),
("metal-measured (an M4).", "", "metal-measured"),
]
bad = [
("", "", "an empty marker"),
("measured on an M4", "", "a value outside the vocabulary"),
("metal-meausred (an M4)", "", "a misspelled value"),
("metal-measured", "", "a measurement with no evidence"),
("metal-takes", "", "a plain-Metal claim with no evidence"),
("metal-documented", "", "a documented refusal with no citation"),
("metal-measured (the call asserts)", "", "a measurement that names no device or release"),
("metal-takes (plain Metal returns)", "", "a plain-Metal claim that names no device"),
("delegated", "TextureProblem", "`delegated` naming no enum"),
("delegated(ViewProblem)", "TextureProblem", "`delegated` naming another enum"),
("delegated(TextureProblem)", "", "`delegated` on a variant that forwards nothing"),
("Device", "", "a value of the wrong case"),
]
bad_news = []
for marker, payload, want in good:
value, _, complaint = parse_basis(marker, payload)
if value != want:
bad_news.append(f"`Basis: {marker}` read as {value!r} ({complaint}), not {want!r}")
for marker, payload, what in bad:
value, _, complaint = parse_basis(marker, payload)
if value is not None:
bad_news.append(f"`Basis: {marker}` ({what}) was taken as {value!r}")
elif not complaint:
bad_news.append(f"`Basis: {marker}` ({what}) was refused without saying why")
# The marker is the doc comment's last line, and the prose above it is left alone.
prose, marker = split_basis("A thing Metal refuses. Basis: ours")
if (prose, marker) != ("A thing Metal refuses.", "ours"):
bad_news.append(f"split_basis read {(prose, marker)!r}")
if split_basis("No marker here.") != ("No marker here.", None):
bad_news.append("split_basis invented a marker")
# The generated `basis()`: an arm per variant, rustfmt's block form past the width, another
# `Basis:` line another file (which `--check` sees stale), a value `RefusalBasis` lacks refused.
arms = [("Unit", "Basis: ours", "", "Unit"), ("W" * 60, "Basis: device", "", "W" * 60 + " { .. }")]
code, faults = basis_rs([("Gap", arms)], {"Ours", "Device"})
block = " { .. } => {\n RefusalBasis::Device\n }\n"
if faults or " Gap::Unit => RefusalBasis::Ours,\n" not in code or block not in code:
bad_news.append(f"basis_rs wrote {code!r} ({faults})")
if basis_rs([("Gap", [("Unit", "Basis: device", "", "Unit")] + arms[1:])], {"Ours", "Device"})[0] == code:
bad_news.append("basis_rs wrote one file for two `Basis:` lines")
if not basis_rs([("Gap", arms)], {"Ours"})[1]:
bad_news.append("basis_rs took a value `RefusalBasis` has no variant for")
# The `Needs` table, from `Needs::basis`'s arms in rustfmt's forms; and `--check`'s refusal of
# a variant with a site whose basis is not settled, but not of one nothing builds.
needs = (
"impl Needs {\n pub fn basis(&self) -> RefusalBasis {\n match self {\n"
" Needs::AnyOf(_) | Needs::NotRepresentable => {\n RefusalBasis::Device\n"
" }\n Needs::NotImplemented => RefusalBasis::Ours,\n"
" Needs::Measured(_) => RefusalBasis::MetalMeasured,\n }\n }\n}\n"
)
table = kind_basis(needs)
want = {"AnyOf": "device", "NotRepresentable": "device", "NotImplemented": "ours", "Measured": "metal-measured"}
if table != want:
bad_news.append(f"kind_basis read {table!r}")
if [derived_basis("feature", k, want) for k in ({"AnyOf", "NotImplemented"}, {"AnyOf"}, {"computed"})] != ["ours", "device", ""]:
bad_news.append("derived_basis did not follow the `Needs` table")
row = lambda name, state, basis: {"name": name, "state": state, "basis": basis, "sites": "1"}
rows = [row("Followed", "indirect", "device"), row("Lost", "indirect", "-"), row("Unbuilt", "no site", "-")]
if unsettled({"feature": ("", rows)}) != [("Lost", "1")]:
bad_news.append(f"unsettled read {unsettled({'feature': ('', rows)})!r}, not the one lost row")
for line in bad_news:
print("selftest:", line, file=sys.stderr)
if bad_news:
print(f"{len(bad_news)} basis cases failed", file=sys.stderr)
return 1
print(f"basis parse: {len(good)} markers read, {len(bad)} refused; basis.rs: 3 cases; Needs: 3", file=sys.stderr)
return 0
def unsettled(tables):
"""(variant, sites) of each translator refusal with a site whose basis is not settled."""
rows = tables["feature"][1] if "feature" in tables else []
return [(r["name"], r["sites"]) for r in rows if r["state"] != "no site" and r["basis"] == "-"]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true", help="fail when docs/REFUSALS.md or basis.rs is stale")
ap.add_argument("--table", action="store_true", help="print one plain Markdown table, most reachable first")
ap.add_argument("--missing-reach", action="store_true", help="list variants without a reach mark")
ap.add_argument("--missing-basis", action="store_true", help="list refusals whose basis is absent or malformed")
ap.add_argument("--selftest", action="store_true", help="run the basis marker's own cases")
a = ap.parse_args()
if a.selftest:
return selftest()
rt_enums = rt_refusal_enums()
tables, missing, faults = build(rt_enums)
if a.missing_reach:
for s, n in missing:
print(f"{s}\t{n}")
return 0
if a.missing_basis:
for s, n, why in faults:
print(f"{s}\t{n}\t{why}")
return 0
if a.table:
sys.stdout.write(plain_table(tables))
return 0
text = render(tables)
enums = [(enum, enum_arms(file, enum)) for _, enum, file in rt_enums]
code, code_faults = basis_rs(enums, {name for name, _ in enum_variants(ERROR_RS, "RefusalBasis")})
print("".join(f"{fault}\n" for fault in code_faults), end="", file=sys.stderr)
if a.check:
# Structural: the variants, what each blocks, where, and its reach. Sites and line
# numbers drift with every edit and are not checked.
def rows(t):
out = []
for line in t.split("\n"):
f = line.split(" | ")
if line.startswith("| `") and len(f) == 6:
out.append((f[0], f[1], f[2], f[3], f[5]))
return out
old = OUT.read_text() if OUT.exists() else ""
if rows(old) != rows(text):
stale = sorted(set(rows(old)) ^ set(rows(text)))
for r in stale[:10]:
print("changed:", " | ".join(r)[:200], file=sys.stderr)
print("docs/REFUSALS.md is stale: rerun scripts/refusal-surface/refusal_surface.py", file=sys.stderr)
return 1
if missing:
print(f"{len(missing)} variants without a reach mark (--missing-reach)", file=sys.stderr)
return 1
if unsettled(tables):
for name, sites in unsettled(tables):
print(f"feature::{name}: built at {sites}, with no basis this follows", file=sys.stderr)
print("a translator refusal whose helper is not followed: settle it in follow()", file=sys.stderr)
return 1
if faults:
for s, n, why in faults[:20]:
print(f"{s}::{n}: its `Basis:` {why}", file=sys.stderr)
print(
f"{len(faults)} refusals whose basis is absent or malformed (--missing-basis). Every "
"variant of the runtime's refusal enums carries a last doc-comment line `Basis: <value> (the "
"evidence)`; a refusal whose basis is not settled says `Basis: unknown (why)` rather "
"than nothing.",
file=sys.stderr,
)
return 1
if code_faults or (BASIS_RS.read_text() if BASIS_RS.exists() else "") != code:
print(f"{BASIS_RS.relative_to(ROOT)} is stale: rerun the script", file=sys.stderr)
return 1
return 0
OUT.write_text(text)
print(
f"wrote {OUT.relative_to(ROOT)}; {len(missing)} variants without a reach mark, "
f"{len(faults)} without a basis",
file=sys.stderr,
)
if code_faults:
return 1
BASIS_RS.write_text(code)
print(f"wrote {BASIS_RS.relative_to(ROOT)}: " + ", ".join(f"{e} {len(v)}" for e, v in enums), file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())