Skip to content

Editorial diagram design for Claude Code, Codex, GitHub Copilot, Cursor, Factory Droid, Qoder, and Pi. 45 diagram types. Self-contained HTML + SVG. No shadows. No Mermaid slop.

fix(verifiers): parse slopegraph, ridgeline and bubble markup as a browser does (#230)

0xDarkMatter62990f4aaf0a
diff --git a/scripts/test-verify-bubble.py b/scripts/test-verify-bubble.py
index 068f08e..b5cdbce 100644
--- a/scripts/test-verify-bubble.py
+++ b/scripts/test-verify-bubble.py
@@ -456,11 +456,15 @@ def run_cases(h: Harness) -> int:
)
# ── Malformed markup: findings, never tracebacks, never silence ───────
+ # The browser reads an unquoted value up to the next whitespace or `>`,
+ # so this circle declares data-size="broken" and nothing else the contract
+ # needs. The checker reads exactly that and reports what it finds.
h.expect_finding(
- "a data-size circle whose attributes cannot be parsed is reported",
+ "an unquoted data-size circle is read as the browser reads it, and its "
+ "missing name is reported",
document(' <circle data-size=broken cx="100" cy="100" r="10"/>\n',
honest_block(), TICKS),
- r"could not be parsed",
+ r"declares data-size but no data-name",
)
h.expect_finding(
"a bubble without data-name is reported",
@@ -481,6 +485,235 @@ def run_cases(h: Harness) -> int:
r"not a finite\s+number",
)
+ # ── Markup is read as the browser reads it ────────────────────────────
+ # A regex tag matcher stops at the first `>` it sees, so a quoted `>`
+ # before an attribute hid that attribute from the checker while Chromium
+ # honoured it. Every case here is a shape the browser parses one way; the
+ # checker must parse it the same way, in both polarities.
+ peers = honest_block(HONEST_PEERS, focal="none")
+ stream = bubble("Stream", 150, 1.5, 900)
+ stream_nudged = bubble("Stream", 150, 1.5, 900, drawn_cx=cx(150) + 8)
+
+ h.expect_finding(
+ "an ancestor <g> hiding its transform behind a quoted > is still reported",
+ document(' <g data-note=">" transform="translate(0 -80)">\n', honest_block(),
+ " </g>\n", TICKS),
+ r"bubble 'Stream' carries an ancestor <g>/<svg> transform",
+ )
+ h.expect_finding(
+ "an ancestor <g> hiding an inline style transform behind a quoted > is reported",
+ document(' <g data-note=">" style="translate: 0 80px">\n', honest_block(),
+ " </g>\n", TICKS),
+ r"bubble 'Stream' carries an ancestor <g>/<svg> style transform",
+ )
+ h.expect_clean(
+ "an honest bubble with a quoted > before its bindings is parsed and passes",
+ document(peers, stream.replace(" <circle ", ' <circle data-note=">" ', 1),
+ TICKS),
+ )
+ h.expect_only_one(
+ "a dishonest bubble with a quoted > before its bindings is still reported",
+ document(peers, stream_nudged.replace(" <circle ", ' <circle data-note=">" ', 1),
+ TICKS),
+ r"bubble 'Stream' declares x=150 .* never nudge",
+ )
+ h.expect_finding(
+ "a label with a quoted > before its bindings is still bound and checked",
+ document(honest_block(), TICKS,
+ label("Edge", cx(100), cy(1.0) - 34, text="QUEUE").replace(
+ " <text ", ' <text data-note=">" ', 1)),
+ r"the visible text and the binding must agree",
+ )
+ h.expect_finding(
+ "a tick hiding a transform behind a quoted > is reported",
+ document(honest_block(), tick("x", 0, extra='data-note=">" transform="translate(40 0)"'),
+ tick("x", 500), tick("y", 0), tick("y", 4)),
+ r"bound label \(0\) carries transform",
+ )
+
+ # Three carriers reach the renderer; the `transform` attribute is only the
+ # most visible. Each is refused on the element and on an ancestor.
+ h.expect_finding(
+ "an inline style transform on a bubble is reported",
+ document(honest_block(),
+ bubble("Slid", 250, 2.5, 300,
+ extra='style="transform: translateY(80px)"'), TICKS),
+ r"bubble 'Slid' carries style=.*\(the transform property\)",
+ )
+ h.expect_finding(
+ "an inline CSS r property on a bubble replaces the verified radius and is reported",
+ document(honest_block(),
+ bubble("Grown", 250, 2.5, 300, extra='style="r: 60px"'), TICKS),
+ r"bubble 'Grown' carries style=.*\(the r property\)",
+ )
+ h.expect_finding(
+ "an inline translate property on a bound label is reported",
+ document(honest_block(), TICKS,
+ label("Edge", cx(100), cy(1.0) - 34, extra='style="translate: 40px 0"')),
+ r"bound label .* carries style=.*\(the translate property\)",
+ )
+ h.expect_finding(
+ "a vendor-prefixed transform on an ancestor group's inline style is reported",
+ document(' <g style="-webkit-transform: translateY(80px)">\n', honest_block(),
+ " </g>\n", TICKS),
+ r"carries an ancestor <g>/<svg> style transform",
+ )
+ h.expect_clean(
+ "an inline text-transform on a bound label is not read as a transform",
+ document(honest_block(), TICKS,
+ label("Edge", cx(100), cy(1.0) - 34,
+ extra='style="text-transform: uppercase; display: block"')),
+ )
+ h.expect_finding(
+ "a CSS translate declaration in a style block is reported",
+ "<style>circle { translate: 0 80px; }</style>"
+ + document(honest_block(), TICKS),
+ r"a CSS `translate` declaration",
+ )
+ h.expect_finding(
+ "a vendor-prefixed CSS transform declaration in a style block is reported",
+ "<style>.bubble {\n -webkit-transform: translateY(80px);\n}</style>"
+ + document(honest_block(), TICKS),
+ r"a CSS `transform` declaration",
+ )
+
+ # First-wins, both polarities: the browser applies the FIRST of a repeated
+ # attribute and the rest are not in the document at all, so the checker
+ # must report exactly when that first one lies.
+ h.expect_clean(
+ "a duplicated style on an ancestor keeps the browser's first, honest value",
+ document(' <g style="opacity: 1" style="transform: translateY(80px)">\n',
+ honest_block(), " </g>\n", TICKS),
+ )
+ h.expect_finding(
+ "a duplicated style on an ancestor keeps the browser's first, dishonest value",
+ document(' <g style="transform: translateY(80px)" style="opacity: 1">\n',
+ honest_block(), " </g>\n", TICKS),
+ r"carries an ancestor <g>/<svg> style transform",
+ )
+ h.expect_finding(
+ "a duplicated r is read first-wins, so an inflated first r is reported",
+ document(peers, stream.replace(
+ ' r="%g"' % radius(900), ' r="%g" r="%g"' % (radius(900) + 6, radius(900)), 1),
+ TICKS),
+ r"bubble 'Stream' declares size 900",
+ )
+ h.expect_clean(
+ "a duplicated r whose first value is honest still passes",
+ document(peers, bubble("Stream", 150, 1.5, 900,
+ extra='r="%g"' % (radius(900) + 6)), TICKS),
+ )
+
+ h.expect_clean(
+ "a self-closing <g/> with a transform encloses nothing and is not reported",
+ document(' <g transform="translate(0 80)"/>\n', honest_block(), TICKS),
+ )
+ h.expect_clean(
+ "a commented-out ancestor transform is not read as live markup",
+ document(' <!-- <g transform="translate(0 80)"> -->\n', honest_block(), TICKS),
+ )
+ h.expect_clean(
+ "an end tag inside a quoted attribute does not end a bound label's text",
+ document(honest_block(), TICKS,
+ label("Edge", cx(100), cy(1.0) - 34).replace(
+ ">EDGE</text>", '><tspan data-note="</text>">EDGE</tspan></text>', 1)),
+ )
+ h.expect_only_one(
+ "upper-case tag and attribute names are read case-insensitively, as the browser does",
+ document(peers, stream_nudged.replace(
+ ' <circle data-name="Stream" data-x=', ' <CIRCLE DATA-NAME="Stream" DATA-X=', 1),
+ TICKS),
+ r"bubble 'Stream' declares x=150 .* never nudge",
+ )
+ h.expect_finding(
+ "a broken attribute quote never crashes the checker and never passes",
+ document(honest_block().replace('data-x="150"', 'data-x="150', 1), TICKS),
+ r".",
+ )
+
+ # ── CSS comments are whitespace to the browser ────────────────────────
+ # `/**/transform:` is a live declaration: the browser drops the comment
+ # before it tokenizes, while a regex anchored to a declaration boundary
+ # walked past it. Each carrier is held to that, and a comment that merely
+ # mentions the property is not a declaration - both polarities.
+ h.expect_finding(
+ "a comment-prefixed inline transform on a bubble is reported",
+ document(honest_block(),
+ bubble("Slid", 250, 2.5, 300,
+ extra='style="/**/transform: translateX(80px)"'), TICKS),
+ r"bubble 'Slid' carries style=.*\(the transform property\)",
+ )
+ h.expect_finding(
+ "a comment-prefixed inline transform on a bound label is reported",
+ document(honest_block(), TICKS,
+ label("Edge", cx(100), cy(1.0) - 34,
+ extra='style="/**/transform: translateX(80px)"')),
+ r"bound label .* carries style=.*\(the transform property\)",
+ )
+ h.expect_finding(
+ "a comment-prefixed inline transform on an ancestor <g> is reported",
+ document(' <g style="/**/transform: translateX(80px)">\n', honest_block(),
+ " </g>\n", TICKS),
+ r"carries an ancestor <g>/<svg> style transform",
+ )
+ h.expect_finding(
+ "a <style> rule with a comment before the property is reported",
+ "<style>circle { /* nudge */ transform: translate(0, 40px); }</style>"
+ + document(honest_block(), TICKS),
+ r"a CSS `transform` declaration",
+ )
+ # The <style> opens on line 1 and the declaration sits on line 3 behind a
+ # two-line comment. The finding must say 3: a comment stripped to nothing
+ # would shift every later line up.
+ h.expect_finding(
+ "a <style> declaration behind a multi-line comment is reported on its own line",
+ "<style>/* header\n comment */\ncircle { transform: translate(0, 40px); }"
+ "</style>" + document(honest_block(), TICKS),
+ r":3: a CSS `transform` declaration",
+ )
+ h.expect_clean(
+ "a <style> comment that merely mentions transform: is not read as a declaration",
+ "<style>/* no transforms here;\n transform: none was the old rule */\n"
+ ".bubble { stroke: none; }</style>" + document(honest_block(), TICKS),
+ )
+ h.expect_clean(
+ "an inline style comment that merely mentions transform: is not read as a declaration",
+ document(honest_block(), TICKS,
+ label("Edge", cx(100), cy(1.0) - 34,
+ extra='style="stroke: none; /* was:\n transform: none */"')),
+ )
+
+ # ── Scope is read from the raw text as well as through the parser ────
+ # An unclosed quote turns the whole tag into character data for
+ # HTMLParser, so a file whose ONLY bubble signal is that tag emitted no
+ # <circle> and was skipped as out of scope - a fail-open. The raw text
+ # (HTML comments removed) claims it and the lost tag is reported. Neither
+ # the filename nor the description names the family in any of these.
+ plain_head = HEAD.replace("Bubble chart fixture.", "Services fixture.")
+ h.expect_finding(
+ "a broken-quoted <circle data-size> that is the file's only signal is "
+ "reported, not skipped",
+ plain_head + TICKS
+ + " <circle data-name='A' data-x='1' data-y='2' data-size=\"9 cx='81.8' "
+ "cy='230' r='4.2'/>\n" + TAIL,
+ r"declares data-size but no complete <circle> could be parsed",
+ name="fixture.html",
+ )
+ h.expect_out_of_scope(
+ "a commented-out <circle data-size> as the file's only signal is out of scope",
+ plain_head + TICKS + " <!-- %s -->\n" % bubble("Ghost", 100, 1.0, 400).strip()
+ + TAIL,
+ "fixture.html",
+ )
+ h.expect_finding(
+ "a live <circle data-size> behind a quoted > is still claimed and checked",
+ plain_head + peers
+ + stream_nudged.replace(" <circle ", ' <circle data-note=">" ', 1)
+ + TICKS + TAIL,
+ r"bubble 'Stream' declares x=150 .* never nudge",
+ name="fixture.html",
+ )
+
# ── Fail closed ───────────────────────────────────────────────────────
h.expect_finding(
"three bubbles are too few for leave-one-out — refused, not passed",
diff --git a/scripts/test-verify-ridgeline.py b/scripts/test-verify-ridgeline.py
index b5179db..0e8bb94 100644
--- a/scripts/test-verify-ridgeline.py
+++ b/scripts/test-verify-ridgeline.py
@@ -13,6 +13,12 @@ amplitude and pitch rather than memorising the shipped layout: a valid ridgeline
at a different top, pitch and scale must pass, and the budget rules must fire at
BOTH ends on counts the shipped example cannot be mutated into.
+The parsing cases hold the checker to reading markup as a browser does: a
+quoted `>` inside an attribute does not end the tag, a repeated attribute keeps
+its first value, a comment is never live markup, and a transform is refused on
+all three of its carriers (attribute, inline style, <style> rule) — each in
+both polarities, so an honest figure written the odd way still passes.
+
The last case pins the scope treaty with the sibling Line-variant checkers.
`data-bins` on a `<path>` is this contract's vocabulary; `data-series`,
`data-ranks` and `data-layer` belong to the slopegraph, bump and streamgraph
@@ -97,6 +103,18 @@ def case(failures, directory, name, source, original, expect, describe):
print("OK: %s is rejected" % describe)
+def accept(failures, directory, name, source, original, describe):
+ """One mutation the browser renders honestly: a real edit, and accepted."""
+ if source == original:
+ failures.append("could not build the %s fixture (anchor moved)" % name)
+ return
+ code, output = run(write(directory, "%s.html" % name, source))
+ if code != 0:
+ failures.append("%s was rejected: %s" % (describe, output.strip()))
+ else:
+ print("OK: %s is accepted" % describe)
+
+
def hump(n_bins, peak_at, height=12, step=3):
"""A closed distribution: zero at both ends, one interior peak."""
values = []
@@ -454,6 +472,274 @@ def main() -> int:
"a falsified bin in single-quoted attributes",
)
+ # 17b. Markup is read as the browser reads it. A regex tag matcher
+ # stops at the first `>` it sees, so a quoted `>` before an
+ # attribute hid that attribute from the checker while Chromium
+ # honoured it. Every case here is a shape the browser parses one
+ # way; the checker must parse it the same way, in both polarities.
+ NAME_LABEL = ('<text data-ridge="checkout-api" data-role="name" x="304" '
+ 'y="323.5"')
+ case(
+ failures, directory, "quoted-gt-ancestor",
+ source.replace(FOCAL_PATH,
+ '<g data-note=">" transform="translate(0 8)">' + FOCAL_PATH
+ + "</g>", 1),
+ source, "an ancestor <g>/<svg> transform",
+ "an ancestor <g> hiding its transform behind a quoted >",
+ )
+ case(
+ failures, directory, "quoted-gt-ancestor-style",
+ source.replace(FOCAL_PATH,
+ '<g data-note=">" style="translate: 0 8px">' + FOCAL_PATH
+ + "</g>", 1),
+ source, "an ancestor <g>/<svg> style transform",
+ "an ancestor <g> hiding an inline style transform behind a quoted >",
+ )
+ accept(
+ failures, directory, "quoted-gt-honest",
+ source.replace('<path data-ridge="checkout-api"',
+ '<path data-note=">" data-ridge="checkout-api"', 1),
+ source, "an honest ridge with a quoted > before its bindings",
+ )
+ case(
+ failures, directory, "quoted-gt-lie",
+ source.replace('<path data-ridge="checkout-api"',
+ '<path data-note=">" data-ridge="checkout-api"', 1)
+ .replace(FOCAL_D, PRIVATE_AMPLITUDE_D, 1),
+ source, "one amplitude",
+ "a ridge on its own amplitude with a quoted > before its bindings",
+ )
+ case(
+ failures, directory, "quoted-gt-label",
+ source.replace(NAME_LABEL, NAME_LABEL.replace(
+ "<text ", '<text data-note=">" transform="translate(0 56)" ', 1), 1),
+ source, "carries transform=",
+ "a name label hiding a transform behind a quoted >",
+ )
+
+ # Three carriers reach the renderer; the `transform` attribute is only
+ # the most visible. Each is refused on the element and on an ancestor.
+ case(
+ failures, directory, "inline-transform",
+ source.replace('<path data-ridge="checkout-api"',
+ '<path style="transform: translateY(8px)" '
+ 'data-ridge="checkout-api"', 1),
+ source, "(the transform property)",
+ "an inline style transform on a ridge outline",
+ )
+ case(
+ failures, directory, "inline-d",
+ source.replace('<path data-ridge="checkout-api"',
+ '<path style="d: path(\'M 0 0 L 4 4 Z\')" '
+ 'data-ridge="checkout-api"', 1),
+ source, "(the d property)",
+ "an inline CSS d property replacing a verified outline",
+ )
+ case(
+ failures, directory, "inline-rule-transform",
+ source.replace('<line data-ridge="checkout-api" data-role="baseline"',
+ '<line style="transform: translateY(8px)" '
+ 'data-ridge="checkout-api" data-role="baseline"', 1),
+ source, "ridge 'checkout-api' carries style=",
+ "an inline style transform on a baseline rule",
+ )
+ case(
+ failures, directory, "inline-label-translate",
+ source.replace(NAME_LABEL, NAME_LABEL.replace(
+ "<text ", '<text style="translate: 0 56px" ', 1), 1),
+ source, "(the translate property)",
+ "an inline translate property on a bound label",
+ )
+ case(
+ failures, directory, "vendor-ancestor",
+ source.replace(FOCAL_PATH,
+ '<g style="-webkit-transform: translateY(8px)">' + FOCAL_PATH
+ + "</g>", 1),
+ source, "an ancestor <g>/<svg> style transform",
+ "a vendor-prefixed transform on an ancestor group's inline style",
+ )
+ accept(
+ failures, directory, "inline-text-transform",
+ source.replace(NAME_LABEL, NAME_LABEL.replace(
+ "<text ", '<text style="text-transform: uppercase; display: block" ', 1), 1),
+ source, "an inline text-transform on a bound label",
+ )
+ case(
+ failures, directory, "css-translate",
+ source.replace("<style>", "<style>\n svg path { translate: 0 8px; }", 1),
+ source, "CSS `translate` declaration",
+ "a CSS translate declaration in a style block",
+ )
+ case(
+ failures, directory, "css-vendor-transform",
+ source.replace("<style>",
+ "<style>\n svg path {\n -webkit-transform: scaleY(1.1);\n }",
+ 1),
+ source, "CSS `transform` declaration",
+ "a vendor-prefixed CSS transform declaration in a style block",
+ )
+
+ # First-wins, both polarities: the browser applies the FIRST of a
+ # repeated attribute and the rest are not in the document at all, so
+ # the checker must report exactly when that first one lies.
+ accept(
+ failures, directory, "dup-style-honest-first",
+ source.replace(FOCAL_PATH,
+ '<g style="opacity: 1" style="transform: translateY(8px)">'
+ + FOCAL_PATH + "</g>", 1),
+ source, "a duplicated style on an ancestor whose first value is honest",
+ )
+ case(
+ failures, directory, "dup-style-lie-first",
+ source.replace(FOCAL_PATH,
+ '<g style="transform: translateY(8px)" style="opacity: 1">'
+ + FOCAL_PATH + "</g>", 1),
+ source, "an ancestor <g>/<svg> style transform",
+ "a duplicated style on an ancestor whose first value moves the ridge",
+ )
+ case(
+ failures, directory, "dup-d-lie-first",
+ source.replace(FOCAL_D, PRIVATE_AMPLITUDE_D + " " + FOCAL_D, 1),
+ source, "one amplitude",
+ "a duplicated d whose first value is on a private amplitude",
+ )
+ accept(
+ failures, directory, "dup-d-honest-first",
+ source.replace(FOCAL_D, FOCAL_D + " " + PRIVATE_AMPLITUDE_D, 1),
+ source, "a duplicated d whose first value is honest",
+ )
+
+ accept(
+ failures, directory, "self-closing-g",
+ source.replace(FOCAL_PATH, '<g transform="translate(0 8)"/>' + FOCAL_PATH, 1),
+ source, "a self-closing <g/> with a transform, which encloses nothing",
+ )
+ accept(
+ failures, directory, "commented-ancestor",
+ source.replace(FOCAL_PATH,
+ '<!-- <g transform="translate(0 8)"> -->' + FOCAL_PATH, 1),
+ source, "a commented-out ancestor transform",
+ )
+ accept(
+ failures, directory, "end-tag-in-attribute",
+ source.replace('text-anchor="end">checkout-api</text>',
+ 'text-anchor="end"><tspan data-note="</text>">checkout-api'
+ "</tspan></text>", 1),
+ source, "an end tag inside a quoted attribute of a bound label",
+ )
+ case(
+ failures, directory, "upper-case",
+ source.replace('<path data-ridge="checkout-api" data-baseline="320"',
+ '<PATH DATA-RIDGE="checkout-api" DATA-BASELINE="320"', 1)
+ .replace(FOCAL_D, PRIVATE_AMPLITUDE_D, 1),
+ source, "one amplitude",
+ "a ridge on its own amplitude written with upper-case tag and attribute names",
+ )
+
+ # A broken quote must neither crash the checker nor pass the file.
+ broken = source.replace('data-baseline="320"', 'data-baseline="320', 1)
+ if broken == source:
+ failures.append("could not build the broken-quote fixture (anchor moved)")
+ else:
+ code, output = run(write(directory, "broken-quote.html", broken))
+ if code == 0:
+ failures.append("a broken attribute quote was accepted")
+ elif "Traceback" in output:
+ failures.append("a broken attribute quote crashed the checker: %s"
+ % output.strip())
+ else:
+ print("OK: a broken attribute quote neither crashes nor passes")
+
+ # 17c. CSS comments are whitespace to the browser. `/**/transform:` is
+ # a live declaration: the browser drops the comment before it
+ # tokenizes, while a regex anchored to a declaration boundary
+ # walked past it. Each carrier is held to that, and a comment that
+ # merely mentions the property is not a declaration.
+ case(
+ failures, directory, "comment-inline-transform",
+ source.replace('<path data-ridge="checkout-api"',
+ '<path style="/**/transform: translateY(8px)" '
+ 'data-ridge="checkout-api"', 1),
+ source, "(the transform property)",
+ "a comment-prefixed inline transform on a ridge outline",
+ )
+ case(
+ failures, directory, "comment-inline-label",
+ source.replace(NAME_LABEL, NAME_LABEL.replace(
+ "<text ", '<text style="/**/transform: translateY(56px)" ', 1), 1),
+ source, "(the transform property)",
+ "a comment-prefixed inline transform on a bound label",
+ )
+ case(
+ failures, directory, "comment-ancestor",
+ source.replace(FOCAL_PATH,
+ '<g style="/**/transform: translateY(8px)">' + FOCAL_PATH
+ + "</g>", 1),
+ source, "an ancestor <g>/<svg> style transform",
+ "a comment-prefixed inline transform on an ancestor group",
+ )
+ case(
+ failures, directory, "comment-css-transform",
+ source.replace("<style>",
+ "<style>\n svg path { /* lift */ transform: scaleY(1.1); }", 1),
+ source, "CSS `transform`",
+ "a <style> rule with a comment before the property",
+ )
+ accept(
+ failures, directory, "comment-mentions-transform",
+ source.replace("<style>",
+ "<style>\n /* legacy rule;\n transform: none */", 1),
+ source, "a <style> comment that merely mentions transform:",
+ )
+
+ # 17d. Scope is read from the raw text as well as through the parser.
+ # An unclosed quote turns the whole tag into character data for
+ # HTMLParser, so a file whose ONLY ridgeline signal is that tag
+ # emitted no <path> and was skipped as out of scope - a fail-open.
+ # The raw text (HTML comments removed) claims it and the lost tag
+ # is reported; a commented-out declaration claims nothing. Neither
+ # the filename nor the description names the family here.
+ broken_only = ("<html><head><title>weekly figure</title></head><body>"
+ "<svg><title>figure</title><desc>latency by service</desc>"
+ "<path data-ridge='a' data-baseline='100' "
+ "data-bins=\"0,1,0 d='M0 0'/></svg></body></html>")
+ code, output = run(write(directory, "figure.html", broken_only))
+ if code == 0:
+ failures.append("a broken-quoted <path data-bins> as the file's only "
+ "signal was skipped or accepted: %s" % output.strip())
+ elif "no complete <path> could be parsed" not in output:
+ failures.append("a broken-quoted <path data-bins> was reported without "
+ "naming the lost tag: %s" % output.strip())
+ else:
+ print("OK: a broken-quoted <path data-bins> that is the file's only "
+ "signal is reported, not skipped")
+
+ commented_only = broken_only.replace(
+ "<path data-ridge='a' data-baseline='100' data-bins=\"0,1,0 d='M0 0'/>",
+ "<!-- <path data-ridge='a' data-baseline='100' data-bins='0,1,0' "
+ "d='M0 0'/> -->", 1)
+ code, output = run(write(directory, "figure.html", commented_only))
+ if code != 0 or "no ridgeline found" not in output:
+ failures.append("a commented-out <path data-bins> as the file's only "
+ "signal was claimed: %s" % output.strip())
+ else:
+ print("OK: a commented-out <path data-bins> as the file's only signal "
+ "is out of scope")
+
+ plain_synthetic = (synthetic(5, 13)
+ .replace("synthetic ridgeline", "synthetic figure")
+ .replace("ridgeline fixture", "latency fixture"))
+ case(
+ failures, directory, "quoted-gt-claimed",
+ plain_synthetic.replace(
+ '<path data-ridge="r0" data-baseline="100" data-bins="0,12,9,6,3,',
+ '<path data-note=">" data-ridge="r0" data-baseline="100" '
+ 'data-bins="0,12,9,8,3,', 1),
+ plain_synthetic, "one amplitude",
+ "a live <path data-bins> behind a quoted > in a file that names the "
+ "family nowhere else",
+ )
+
# 18. Fail closed on a file that claims the type and yields nothing.
empty = ("<html><head><title>weekly ridgeline</title></head>"
"<body><svg><title>ridgeline of nothing</title></svg></body></html>")
diff --git a/scripts/test-verify-slopegraph.py b/scripts/test-verify-slopegraph.py
index 9f2d241..37f2c04 100644
--- a/scripts/test-verify-slopegraph.py
+++ b/scripts/test-verify-slopegraph.py
@@ -567,12 +567,15 @@ def run_cases(h: Harness) -> int:
r"'Search' draws its to endpoint",
)
+ # The browser reads an unquoted value up to the next whitespace or `>`,
+ # so this is a real series drawn nowhere near its declared values. The
+ # checker reads exactly that and reports what it finds.
h.expect_finding(
- "a <line> declaring data-series whose attributes cannot be parsed is reported",
+ "an unquoted series line is read as the browser reads it, and its lie is reported",
document(honest_rows_block()
+ " <line data-series=unquoted data-from=1 data-to=2 "
"x1=320 y1=40 x2=680 y2=420 stroke='#2d3142'/>\n"),
- r"declares data-series but its attributes could not be parsed",
+ r"series 'unquoted' draws its (from|to) endpoint",
)
h.expect_clean(
@@ -628,6 +631,283 @@ def run_cases(h: Harness) -> int:
document(billions),
)
+ # ── 7. Markup is read as the browser reads it ─────────────────────────
+ # A regex tag matcher stops at the first `>` it sees, so a quoted `>`
+ # before an attribute hid that attribute from the checker while Chromium
+ # honoured it. Every case here is a shape the browser parses one way; the
+ # checker must parse it the same way, in both polarities.
+ search_line = series("Search", 512, 208)
+ search_nudged = series("Search", 512, 208, y2=y(208) - 3)
+ others = honest_rows_block([r for r in ROWS if r[0] != "Search"])
+
+ h.expect_finding(
+ "an ancestor <g> hiding its transform behind a quoted > is still reported",
+ document(' <g data-note=">" transform="translate(0 -80)">\n'
+ + honest_rows_block() + " </g>\n"),
+ r"series 'Search' carries an ancestor <g>/<svg> transform",
+ )
+
+ h.expect_finding(
+ "an ancestor <g> hiding an inline style transform behind a quoted > is reported",
+ document(' <g data-note=">" style="translate: 0 80px">\n'
+ + honest_rows_block() + " </g>\n"),
+ r"series 'Search' carries an ancestor <g>/<svg> style transform",
+ )
+
+ h.expect_clean(
+ "an honest series line with a quoted > before its bindings is parsed and passes",
+ document(search_line.replace(" <line ", ' <line data-note=">" ', 1)
+ + labels("Search", 512, 208) + others),
+ )
+
+ h.expect_finding(
+ "a dishonest series line with a quoted > before its bindings is still reported",
+ document(search_nudged.replace(" <line ", ' <line data-note=">" ', 1)
+ + labels("Search", 512, 208) + others),
+ r"series 'Search' draws its to endpoint.*off by 3\.0 px",
+ )
+
+ h.expect_finding(
+ "a value label with a quoted > before its bindings is still bound and checked",
+ document(honest_rows_block()).replace(
+ ' <text data-series="Search" data-end="to" x="696"',
+ ' <text data-note=">" data-series="Search" data-end="to" x="696"', 1
+ ).replace(">208</text>", ">180</text>", 1),
+ r"series 'Search' prints '180' at its to endpoint but declares 208",
+ )
+
+ h.expect_finding(
+ "a state caption hiding a transform behind a quoted > is reported",
+ document(honest_rows_block()).replace(
+ ' <text data-axis="from"',
+ ' <text data-note=">" transform="translate(0 40)" data-axis="from"', 1),
+ r"bound label \(BEFORE\) carries transform",
+ )
+
+ # Three carriers reach the renderer; the `transform` attribute is only the
+ # most visible. Each is refused on the element and on an ancestor.
+ h.expect_finding(
+ "an inline style transform on a series line is reported",
+ document(search_line.replace(
+ " <line ", ' <line style="transform: translateY(80px)" ', 1)
+ + labels("Search", 512, 208) + others),
+ r"series 'Search' carries style=.*\(the transform property\)",
+ )
+
+ h.expect_finding(
+ "an inline translate property on a bound label is reported",
+ document(honest_rows_block()).replace(
+ ' <text data-series="Search" data-end="from"',
+ ' <text style="translate: 0 40px" data-series="Search" data-end="from"', 1),
+ r"bound label .* carries style=.*\(the translate property\)",
+ )
+
+ h.expect_finding(
+ "an inline CSS y property on a bound label replaces the verified y and is reported",
+ document(honest_rows_block()).replace(
+ ' <text data-series="Search" data-end="from"',
+ ' <text style="y: 400px" data-series="Search" data-end="from"', 1),
+ r"bound label .* carries style=.*\(the y property\)",
+ )
+
+ h.expect_finding(
+ "a vendor-prefixed transform on an ancestor group's inline style is reported",
+ document(' <g style="-webkit-transform: translateY(80px)">\n'
+ + honest_rows_block() + " </g>\n"),
+ r"carries an ancestor <g>/<svg> style transform",
+ )
+
+ h.expect_clean(
+ "an inline text-transform on a bound label is not read as a transform",
+ document(honest_rows_block()).replace(
+ ' <text data-series="Search" data-end="from"',
+ ' <text style="text-transform: uppercase; display: block" '
+ 'data-series="Search" data-end="from"', 1),
+ )
+
+ h.expect_finding(
+ "a CSS translate declaration in a style block is reported",
+ HEAD + "<style>line { translate: 0 80px; }</style>\n"
+ + CAPTIONS + honest_rows_block() + TAIL,
+ r"a CSS `translate` declaration",
+ )
+
+ h.expect_finding(
+ "a vendor-prefixed CSS transform declaration in a style block is reported",
+ HEAD + "<style>.series {\n -webkit-transform: translateY(80px);\n}</style>\n"
+ + CAPTIONS + honest_rows_block() + TAIL,
+ r"a CSS `transform` declaration",
+ )
+
+ # First-wins on an ancestor, both polarities: the browser applies the
+ # first `style`, so the checker must report exactly when that one moves.
+ h.expect_clean(
+ "a duplicated style on an ancestor keeps the browser's first, honest value",
+ document(' <g style="opacity: 1" style="transform: translateY(80px)">\n'
+ + honest_rows_block() + " </g>\n"),
+ )
+
+ h.expect_finding(
+ "a duplicated style on an ancestor keeps the browser's first, dishonest value",
+ document(' <g style="transform: translateY(80px)" style="opacity: 1">\n'
+ + honest_rows_block() + " </g>\n"),
+ r"carries an ancestor <g>/<svg> style transform",
+ )
+
+ # The same rule on a mark's own coordinates: HTML drops a repeated
+ # attribute and keeps the first, so a last-wins reader validates bytes
+ # that are not in the document.
+ h.expect_finding(
+ "a duplicated y2 is read first-wins, so a dishonest first y2 is reported",
+ document(search_line.replace(
+ ' y2="', ' y2="%g" y2="' % (y(208) - 3), 1)
+ + labels("Search", 512, 208) + others),
+ r"series 'Search' draws its to endpoint.*off by 3\.0 px",
+ )
+
+ h.expect_clean(
+ "a duplicated y2 whose first value is honest still passes",
+ document(search_line.replace(
+ ' stroke=', ' y2="%g" stroke=' % (y(208) - 3), 1)
+ + labels("Search", 512, 208) + others),
+ )
+
+ h.expect_clean(
+ "a self-closing <g/> with a transform encloses nothing and is not reported",
+ document(' <g transform="translate(0 80)"/>\n' + honest_rows_block()),
+ )
+
+ h.expect_clean(
+ "a commented-out ancestor transform is not read as live markup",
+ document(' <!-- <g transform="translate(0 80)"> -->\n' + honest_rows_block()),
+ )
+
+ h.expect_clean(
+ "an end tag inside a quoted attribute does not end a bound label's text",
+ document(honest_rows_block()).replace(
+ 'data-role="name" x="272" y="%g">Search<' % (y(512) + 3.5),
+ 'data-role="name" x="272" y="%g"><tspan data-note="</text>">Search</tspan><'
+ % (y(512) + 3.5), 1),
+ )
+
+ h.expect_finding(
+ "upper-case tag and attribute names are read case-insensitively, as the browser does",
+ document(search_nudged.replace(
+ ' <line data-series="Search"', ' <LINE DATA-SERIES="Search"', 1)
+ + labels("Search", 512, 208) + others),
+ r"series 'Search' draws its to endpoint.*off by 3\.0 px",
+ )
+
+ h.expect_finding(
+ "a broken attribute quote never crashes the checker and never passes",
+ document(honest_rows_block()).replace('data-from="512"', 'data-from="512', 1),
+ r".",
+ )
+
+ # ── 8. CSS comments are whitespace to the browser ─────────────────────
+ # `/**/transform:` is a live declaration: the browser drops the comment
+ # before it tokenizes, while a regex anchored to a declaration boundary
+ # walked past it. Each carrier is held to that, and a comment that merely
+ # mentions the property is not a declaration - both polarities.
+ h.expect_finding(
+ "a comment-prefixed inline transform on a series line is reported",
+ document(search_line.replace(
+ " <line ", ' <line style="/**/transform: translateX(80px)" ', 1)
+ + labels("Search", 512, 208) + others),
+ r"series 'Search' carries style=.*\(the transform property\)",
+ )
+
+ h.expect_finding(
+ "a comment-prefixed inline transform on a bound label is reported",
+ document(honest_rows_block()).replace(
+ ' <text data-series="Search" data-end="from"',
+ ' <text style="/**/transform: translateX(80px)" data-series="Search" '
+ 'data-end="from"', 1),
+ r"bound label .* carries style=.*\(the transform property\)",
+ )
+
+ h.expect_finding(
+ "a comment-prefixed inline transform on an ancestor <g> is reported",
+ document(' <g style="/**/transform: translateX(80px)">\n'
+ + honest_rows_block() + " </g>\n"),
+ r"carries an ancestor <g>/<svg> style transform",
+ )
+
+ h.expect_finding(
+ "a <style> rule with a comment before the property is reported",
+ HEAD + "<style>line { /* nudge */ transform: translateY(40px); }</style>\n"
+ + CAPTIONS + honest_rows_block() + TAIL,
+ r"a CSS `transform` declaration",
+ )
+
+ # HEAD is six lines, so the <style> opens on line 7 and the declaration
+ # sits on line 9 behind a two-line comment. The finding must say 9: a
+ # comment stripped to nothing would shift every later line up.
+ h.expect_finding(
+ "a <style> declaration behind a multi-line comment is reported on its own line",
+ HEAD + "<style>/* header\n comment */\nline { transform: translateY(40px); }"
+ "</style>\n" + CAPTIONS + honest_rows_block() + TAIL,
+ r":9: a CSS `transform` declaration",
+ )
+
+ h.expect_clean(
+ "a <style> comment that merely mentions transform: is not read as a declaration",
+ HEAD + "<style>/* no transforms here;\n transform: none was the old rule */\n"
+ "line { stroke: #2d3142; }</style>\n" + CAPTIONS + honest_rows_block() + TAIL,
+ )
+
+ h.expect_clean(
+ "an inline style comment that merely mentions transform: is not read as a declaration",
+ document(honest_rows_block()).replace(
+ ' <text data-series="Search" data-end="from"',
+ ' <text style="stroke: none; /* was:\n transform: none */" '
+ 'data-series="Search" data-end="from"', 1),
+ )
+
+ # ── 9. Scope is read from the raw text as well as through the parser ──
+ # An unclosed quote turns the whole tag into character data for
+ # HTMLParser, so a file whose ONLY slopegraph signal is that tag emitted
+ # no <line> and was skipped as out of scope - a fail-open. The raw text
+ # (HTML comments removed) claims it and the lost tag is reported. Neither
+ # the filename nor the description names the family in any of these.
+ plain_head = HEAD.replace("Slopegraph fixture.", "Latency fixture.")
+
+ h.expect_finding(
+ "a broken-quoted <line data-series> that is the file's only signal is "
+ "reported, not skipped",
+ plain_head + CAPTIONS
+ + ' <line data-series="Search data-from=512 data-to=208 x1=320 y1=72.1 '
+ "x2=680 y2=328.8/>\n" + TAIL,
+ r"declares data-series on a <line> but no complete <line> could be parsed",
+ name="figure.html",
+ )
+
+ h.expect_out_of_scope(
+ "a commented-out <line data-series> as the file's only signal is out of scope",
+ plain_head + CAPTIONS
+ + ' <!-- <line data-series="ghost" data-from="1" data-to="2" x1="320" '
+ 'y1="10" x2="680" y2="410"/> -->\n' + TAIL,
+ "figure.html",
+ )
+
+ h.expect_finding(
+ "a live <line data-series> behind a quoted > is still claimed and checked",
+ plain_head + CAPTIONS
+ + search_nudged.replace(" <line ", ' <line data-note=">" ', 1)
+ + labels("Search", 512, 208) + others + TAIL,
+ r"series 'Search' draws its to endpoint.*off by 3\.0 px",
+ name="figure.html",
+ )
+
+ h.expect_out_of_scope(
+ "data-series on a <path> alone (the bump chart's binding) is not claimed "
+ "by the raw signal",
+ plain_head + ' <line x1="320" y1="40" x2="320" y2="420" stroke="#2d3142"/>\n'
+ ' <path data-series="legacy-http" data-ranks="1,2" d="M320 40 L680 80"/>\n'
+ + TAIL,
+ "figure.html",
+ )
+
# ── The fixture-isolation fix, held in place ──────────────────────────
sentinel = ROOT / "example-slopegraph-fixture.html"
existed = sentinel.exists()
diff --git a/scripts/verify-bubble.py b/scripts/verify-bubble.py
index 24e3767..54f173a 100644
--- a/scripts/verify-bubble.py
+++ b/scripts/verify-bubble.py
@@ -48,6 +48,30 @@ Seven invariants:
so it would define the scale rather than be checked against it, and an
unmeasurable mark is reported rather than skipped.
+Markup is read through the stdlib html.parser.HTMLParser, never a regex, so a
+tag is recognized exactly when a browser would recognize it: a quoted `>`
+inside an attribute value does not end the tag, a repeated attribute keeps its
+FIRST value and the rest are not in the document at all, unquoted values and
+upper-case names parse as their canonical form, and a comment's contents are
+never live markup. The regex tag matcher this replaced stopped at the first
+`>` it saw, so `<g data-note=">" transform="translate(0 -80)">` hid its
+transform from the checker while Chromium applied it to every bubble inside -
+the same fail-open shape verify-block-registry.py retired for the same reason.
+
+No transform may move verified geometry or a bound label, and a transform
+reaches the renderer by three carriers: the `transform` attribute, an inline
+`style="..."`, and a rule in a <style> block. All three are refused, on the
+element and on any ancestor <g>/<svg>, following verify-beeswarm.py; the
+property set in CSS_MOVES_MARK_RE is the invariant, covering what moves or
+resizes a circle (`cx`/`cy`/`r`) and what moves a label or tick (`x`/`y`).
+CSS comments are stripped before any carrier is read, as the browser strips
+them: `/**/transform:` is a live declaration, not a quirk.
+
+Scope is read from the raw text with HTML comments removed, BEFORE the parser,
+so a <circle> whose broken quoting keeps the parser from emitting it still
+claims the file and is reported rather than skipped - the parser is exactly
+what an unclosed quote defeats.
+
The basis for geometry is the `data-x` / `data-y` / `data-size` triple each
bubble circle declares, never the rendered text. The scales are derived from
the set itself (Theil-Sen, leave-one-out), so one dishonest bubble cannot drag
@@ -78,27 +102,44 @@ Exit: 0 clean, 1 findings, 2 usage.
from __future__ import annotations
import argparse
-import html
import math
import re
import sys
+from html.parser import HTMLParser
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ASSET_DIR = ROOT / "skills/diagram-design/assets"
-CIRCLE_RE = re.compile(r"<circle\b(?P<attrs>[^>]*?)/?>", re.IGNORECASE)
-TEXT_RE = re.compile(r"<text\b(?P<attrs>[^>]*)>(?P<body>.*?)</text>", re.IGNORECASE | re.DOTALL)
-COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
-NAMED_RE = re.compile(r"<(?P<tag>title|desc)\b[^>]*>(?P<body>.*?)</(?P=tag)>",
- re.IGNORECASE | re.DOTALL)
-GROUP_OPEN_RE = re.compile(r"<(?:g|svg)\b(?P<attrs>[^>]*?)(?P<selfclose>/?)>", re.IGNORECASE)
-GROUP_CLOSE_RE = re.compile(r"</(?:g|svg)\s*>", re.IGNORECASE)
-STYLE_RE = re.compile(r"<style\b[^>]*>(?P<body>.*?)</style>", re.IGNORECASE | re.DOTALL)
-# `transform:` but not `text-transform:`. The full-editorial template uses the
-# latter, so an unguarded pattern would report every editorial variant.
-CSS_TRANSFORM_RE = re.compile(r"(?<![\w-])transform\s*:", re.IGNORECASE)
-TAG_RE = re.compile(r"<[^>]+>")
+# Every CSS property that can move or reshape a verified mark WITHOUT touching
+# the attributes this checker reads. The enumeration IS the invariant - it is
+# copied from verify-beeswarm.py, where it had already been wrong twice
+# (`transform:` alone missed `style="transform: ..."`, and once that was fixed
+# `style="translate: 80px 0"` walked past it because CSS Transforms Level 2
+# splits the transform into four properties). Three families reach a mark:
+#
+# transform / translate / rotate / scale the four transform properties;
+# the individual three compose WITH `transform`, so each is its own door
+# cx / cy / r / x / y SVG geometry properties. CSS wins
+# over the presentation attribute, so `style="r: 40px"` on a bubble
+# replaces the very radius that was verified, and x/y do the same to a
+# bound label or tick - a more direct lie than any transform
+# offset and its path/distance/position/anchor/rotate longhands
+# CSS motion path, which places the element somewhere else entirely
+#
+# Anchored to a declaration start, so `text-transform:` (the editorial skin
+# uses it), `display:` and `--custom:` never match, and the `rotate` inside
+# `transform: rotate(45deg)` is read once as the property and never as the
+# function in its value. A vendor prefix is optional so `-webkit-transform:`
+# is not a free pass.
+CSS_MOVES_MARK_RE = re.compile(
+ r"(?:^|[{;}\n])\s*(?:-(?:webkit|moz|ms|o)-)?"
+ r"(?P<prop>transform|translate|rotate|scale"
+ r"|cx|cy|r|x|y"
+ r"|offset(?:-(?:path|distance|position|anchor|rotate))?)"
+ r"\s*:",
+ re.IGNORECASE,
+)
# The COMPLETE numeric token an author may print: sign, comma-grouped
# thousands, decimals, leading-dot decimals, exponents. Matching only the
# first fragment is how "512,000" once agreed with metadata that said 512.
@@ -106,14 +147,18 @@ NUMBER_RE = re.compile(
r"[-+]?(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?"
)
DIGIT_RE = re.compile(r"\d")
-
-# Both quote styles: matching only double quotes drops a single-quoted circle
-# from the verified set without a word, which is exactly how a lie ships.
-ATTR_RE = re.compile(
- r"""(?P<name>[\w:-]+)\s*=\s*(?P<quote>["'])(?P<value>.*?)(?P=quote)""",
- re.DOTALL,
-)
+# A CSS comment is whitespace to the browser, so `/**/transform:` is a live
+# declaration. CSS_MOVES_MARK_RE allows only whitespace between a declaration
+# boundary and the property name, which let a comment sitting there hide the
+# property from it while Chromium applied it. Non-greedy and DOTALL: a comment
+# spans lines, and a stylesheet holds many. See css_moves_mark.
+CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
+# Detection only - deliberately a text search over the raw bytes, HTML comments
+# removed, so a file that so much as mentions the binding in live markup is
+# held to the contract even when the parser cannot read the tag that binds it.
+# See declares_bubble.
DECLARES_BUBBLE_RE = re.compile(r"\bdata-size\s*=", re.IGNORECASE)
+HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
# The accent stroke on either skin, hex or rgba. The focal count keys on the
# STROKE because the fill is a translucent tint the paper shows through; the
@@ -136,38 +181,222 @@ TICK_TOLERANCE = 6.0 # px, tick position vs the scale the bubbles set
LABEL_TOLERANCE = 0.5 # px, slack before a label counts as another bubble's
OVERLAP_SLACK = 0.5 # px, separation below which two bubbles overlap
+GROUP_TAGS = ("g", "svg") # the only ancestors whose transform is inherited
+BODY_TAGS = ("text", "title", "desc", "style") # elements whose character data is read
+MARK_TAGS = ("circle",) # the element this contract binds
+
+
+# === PARSING =================================================================
+
+
+class Element:
+ """One start tag this checker cares about, as the browser tokenized it."""
+
+ __slots__ = ("tag", "attrs", "offset", "line", "body", "ancestor")
+
+ def __init__(self, tag, attrs, offset, line, ancestor):
+ self.tag = tag
+ self.attrs = attrs # first-wins dict, names lower-cased, values unescaped
+ self.offset = offset # offset of `<` in the source, for ordering
+ self.line = line
+ self.body = "" # character data up to the matching end tag
+ self.ancestor = ancestor # how the nearest transformed <g>/<svg> moves it, or None
+
class Bubble:
- __slots__ = ("name", "x", "y", "size", "cx", "cy", "r", "accent", "offset")
+ __slots__ = ("name", "x", "y", "size", "cx", "cy", "r", "accent", "line")
- def __init__(self, name, x, y, size, cx, cy, r, accent, offset):
+ def __init__(self, name, x, y, size, cx, cy, r, accent, line):
self.name = name
self.x, self.y, self.size = x, y, size
self.cx, self.cy, self.r = cx, cy, r
self.accent = accent
- self.offset = offset
+ self.line = line
+
+def first_wins(attrs) -> dict:
+ """Attributes as the browser keeps them: on a repeat, the FIRST wins.
-def line_of(source: str, offset: int) -> int:
- return source.count("\n", 0, offset) + 1
+ HTML parsing drops a duplicate attribute rather than overwriting the one
+ already on the token, so a second `r` on a circle is not merely ignored -
+ it is not in the document at all. A dict comprehension does the opposite,
+ and that gap is a fail-open every caller inherits: a circle carrying a
+ dishonest first `r` and an honest second renders the dishonest radius
+ while a last-wins reader checks, and passes, bytes the browser threw away.
+ A present-but-valueless attribute is an empty string, not an absent one.
+ """
+ seen = {}
+ for name, value in attrs:
+ seen.setdefault(name, "" if value is None else value)
+ return seen
-def blank_comments(source: str) -> str:
- """Comments out, length and line numbers preserved.
+class _Scanner(HTMLParser):
+ """Collect circles, texts, title/desc and style elements with ancestry.
- Markup inside a comment is not rendered, so treating it as data reports a
- commented-out old draft as a live defect. Replacing each comment with
- spaces of the same length keeps every later offset and line number honest.
+ HTMLParser already lowercases tag and attribute names, tolerates unquoted
+ values and whitespace around `=`, unescapes entities, keeps a quoted `>`
+ inside the value it belongs to, and never invokes handle_starttag for
+ tag-like text inside a comment or inside <script>/<style> raw text - each
+ of those is exactly a case a regex tag matcher mishandles. Ancestry is
+ tracked for <g>/<svg> only, the elements whose transform a child inherits.
"""
- return COMMENT_RE.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), source)
+
+ def __init__(self, source: str):
+ super().__init__(convert_charrefs=True)
+ self.circles: list = []
+ self.texts: list = []
+ self.named: list = [] # <title> and <desc>
+ self.styles: list = []
+ self.error = None
+ self._groups: list = [] # (tag, how) per open <g>/<svg>
+ self._open: list = [] # (tag, Element) per open body element
+ self._line_starts = [0]
+ for index, char in enumerate(source):
+ if char == "\n":
+ self._line_starts.append(index + 1)
+ try:
+ self.feed(source)
+ self.close()
+ except Exception as exc: # noqa: BLE001 - any parser failure fails closed
+ self.error = "%s: %s" % (type(exc).__name__, exc)
+
+ def _offset(self) -> int:
+ line, column = self.getpos()
+ return self._line_starts[line - 1] + column
+
+ def _ancestor(self):
+ for _tag, how in reversed(self._groups):
+ if how is not None:
+ return how
+ return None
+
+ def handle_starttag(self, tag, attrs):
+ self._start(tag, first_wins(attrs), closes=False)
+
+ def handle_startendtag(self, tag, attrs):
+ self._start(tag, first_wins(attrs), closes=True)
+
+ def _start(self, tag, attrs, closes):
+ if tag in GROUP_TAGS:
+ if not closes:
+ how = None
+ if "transform" in attrs:
+ how = "an ancestor <g>/<svg> transform"
+ elif transform_carrier(attrs) is not None:
+ how = "an ancestor <g>/<svg> style transform"
+ self._groups.append((tag, how))
+ return
+ if tag not in MARK_TAGS and tag not in BODY_TAGS:
+ return
+ element = Element(tag, attrs, self._offset(), self.getpos()[0], self._ancestor())
+ if tag == "circle":
+ self.circles.append(element)
+ return
+ if tag == "text":
+ self.texts.append(element)
+ elif tag == "style":
+ self.styles.append(element)
+ else:
+ self.named.append(element)
+ if not closes:
+ self._open.append((tag, element))
+
+ def handle_endtag(self, tag):
+ stack = self._groups if tag in GROUP_TAGS else self._open if tag in BODY_TAGS else None
+ if stack is None:
+ return
+ # Pop back to the matching open tag - an unclosed inner element ends
+ # with its parent, as it does in the browser's tree.
+ for index in range(len(stack) - 1, -1, -1):
+ if stack[index][0] == tag:
+ del stack[index:]
+ return
+
+ def handle_data(self, data):
+ if self._open:
+ # Innermost only: a <title> tooltip inside a <text> is not part of
+ # the rendered label, and the browser does not draw it either.
+ self._open[-1][1].body += data
+
+
+def parse_document(source: str) -> _Scanner:
+ return _Scanner(source)
def attrs_of(raw: str) -> dict:
- return {m.group("name"): m.group("value") for m in ATTR_RE.finditer(raw)}
+ """First-wins attributes of one tag's raw attribute text, via the parser."""
+
+ class _One(HTMLParser):
+ def __init__(self):
+ super().__init__(convert_charrefs=True)
+ self.attrs = {}
+
+ def handle_starttag(self, tag, attrs):
+ self.attrs = first_wins(attrs)
+
+ handle_startendtag = handle_starttag
+
+ scanner = _One()
+ scanner.feed("<x " + raw + ">")
+ scanner.close()
+ return scanner.attrs
+
+
+def transform_carrier(attrs: dict):
+ """How this element carries a transform, phrased for the finding, or None.
+
+ A transform reaches the renderer by three carriers and the `transform`
+ ATTRIBUTE is only the most visible one. Reading the attribute alone lets
+ `style="transform: translateY(...)"` on a bubble, a bound label, a tick or
+ an ancestor group move the rendered mark after its raw coordinates were
+ validated. The third carrier, a rule in a <style> block, is reported
+ separately because nothing here can tell which marks such a rule selects.
+ """
+ if "transform" in attrs:
+ return "transform=%r" % attrs["transform"]
+ style = attrs.get("style")
+ if style is not None:
+ found = css_moves_mark(style)
+ if found is not None:
+ return "style=%r (the %s property)" % (style, found.group("prop").lower())
+ return None
+
+
+def css_moves_mark(css: str):
+ """The first mark-moving declaration in CSS text, read past comments, or None.
+
+ Every carrier goes through here - an inline style, an ancestor's inline
+ style, a <style> block - because the browser drops `/* ... */` before it
+ tokenizes, and CSS_MOVES_MARK_RE must see what the browser sees:
+ `style="/**/transform: translateX(80px)"` moved a bubble while the
+ anchored regex walked past the comment. Each comment is blanked to
+ whitespace of the SAME length, newlines kept, so the searched text is
+ aligned with the original character for character: every offset in the
+ returned match is an offset into `css` as written, and a <style> finding
+ that counts newlines up to the property names the right line.
+ """
+ stripped = CSS_COMMENT_RE.sub(
+ lambda found: re.sub(r"[^\n]", " ", found.group()), css)
+ return CSS_MOVES_MARK_RE.search(stripped)
+
+
+def declares_bubble(source: str) -> bool:
+ """Does the raw text, HTML comments removed, declare data-size anywhere?
+
+ Read BEFORE the parser, because the parser is exactly what a broken quote
+ defeats: `<circle data-size="9` with no closing quote is character data
+ to HTMLParser, no <circle> is ever emitted, and a file whose only bubble
+ signal was that tag would otherwise be skipped as out of scope - a
+ fail-open. The raw signal claims the file and check_source then reports
+ the tag the parser could not read. Comments are stripped first so a
+ commented-out draft bubble does not claim an unrelated file.
+ """
+ return DECLARES_BUBBLE_RE.search(HTML_COMMENT_RE.sub("", source)) is not None
def plain(body: str) -> str:
- return html.unescape(TAG_RE.sub("", body)).strip()
+ return body.strip()
def number(value):
@@ -257,9 +486,9 @@ def outliers(points: list, tolerance: float) -> list:
return found
-def named_text(source: str) -> str:
+def named_text(doc: _Scanner) -> str:
"""The accessible name and description, where a figure says what it is."""
- return " ".join(plain(m.group("body")) for m in NAMED_RE.finditer(source)).casefold()
+ return " ".join(plain(element.body) for element in doc.named).casefold()
def looks_like_bubble(path: Path, source: str) -> bool:
@@ -270,72 +499,35 @@ def looks_like_bubble(path: Path, source: str) -> bool:
that claims it while declaring nothing parseable is the fail-closed case,
not a pass. Scoped to bubble-specific signals only: `data-size` rather
than `data-series`, so this checker and `verify-slopegraph.py` never claim
- one another's files.
+ one another's files. A declaration inside an HTML comment is not live
+ markup and claims nothing.
"""
if path.name.startswith("example-bubble"):
return True
- if DECLARES_BUBBLE_RE.search(source):
+ if declares_bubble(source):
return True
- described = named_text(source)
+ described = named_text(parse_document(source))
return "bubble chart" in described or "bubble plot" in described
-def transformed_spans(source: str) -> list:
- """Offset ranges enclosed by a <g>/<svg> that carries a transform.
-
- Element-level transforms are easy to see; an ancestor's is not, and shifts
- everything inside it identically - exactly the change that leaves all
- internal consistency intact while moving every mark on the page.
- """
- events = []
- for match in GROUP_OPEN_RE.finditer(source):
- if match.group("selfclose"):
- continue
- events.append((match.start(), 0, "transform" in attrs_of(match.group("attrs"))))
- for match in GROUP_CLOSE_RE.finditer(source):
- events.append((match.start(), 1, False))
- events.sort()
- stack, spans = [], []
- for position, kind, transformed in events:
- if kind == 0:
- stack.append((position, transformed))
- elif stack:
- start, was_transformed = stack.pop()
- if was_transformed:
- spans.append((start, position))
- # An unclosed transformed group covers everything after it.
- for start, was_transformed in stack:
- if was_transformed:
- spans.append((start, len(source)))
- return spans
-
-
-def parse_bubbles(source: str, findings: list, name: str) -> list:
+def parse_bubbles(doc: _Scanner, findings: list, name: str) -> list:
"""Bubble circles, with anything unparseable reported rather than dropped."""
bubbles = []
- for match in CIRCLE_RE.finditer(source):
- raw = match.group("attrs")
- attrs = attrs_of(raw)
+ for element in doc.circles:
+ attrs = element.attrs
+ line = element.line
if "data-size" not in attrs:
# A <circle> with no data-size is scenery - a paper underlay, a
- # legend swatch, a dot-grid cell - and skipping it is correct. But
- # one whose raw text DOES declare data-size and still parsed to
- # nothing is markup this checker cannot read, and dropping it
- # silently is how a lie ships.
- if DECLARES_BUBBLE_RE.search(raw):
- findings.append(
- "%s:%d: a <circle> declares data-size but its attributes could "
- "not be parsed — the checker will not silently skip markup it "
- "cannot read. Use plain quoted attributes"
- % (name, line_of(source, match.start()))
- )
+ # legend swatch, a dot-grid cell - and skipping it is correct. The
+ # parser reads every tag the browser reads, so there is no
+ # "declared but unparseable" case left to report here.
continue
label = attrs.get("data-name")
if label is None:
findings.append(
"%s:%d: a bubble declares data-size but no data-name — an unnamed "
"bubble cannot be labelled or cross-checked"
- % (name, line_of(source, match.start()))
+ % (name, line)
)
continue
missing = [key for key in ("data-x", "data-y", "cx", "cy", "r")
@@ -344,7 +536,7 @@ def parse_bubbles(source: str, findings: list, name: str) -> list:
findings.append(
"%s:%d: bubble %r is missing %s — a bubble must declare all three "
"values and all three drawn quantities or it cannot be verified"
- % (name, line_of(source, match.start()), label, ", ".join(missing))
+ % (name, line, label, ", ".join(missing))
)
continue
parsed = [number(attrs[key])
@@ -353,7 +545,7 @@ def parse_bubbles(source: str, findings: list, name: str) -> list:
findings.append(
"%s:%d: bubble %r has a value or coordinate that is not a finite "
"number — cannot verify its position or area"
- % (name, line_of(source, match.start()), label)
+ % (name, line, label)
)
continue
if parsed[2] <= 0:
@@ -363,71 +555,70 @@ def parse_bubbles(source: str, findings: list, name: str) -> list:
findings.append(
"%s:%d: bubble %r declares data-size=%g — area cannot encode a "
"non-positive value. Omit the item and note the omission in the "
- "source line" % (name, line_of(source, match.start()), label,
- parsed[2])
+ "source line" % (name, line, label, parsed[2])
)
continue
if parsed[5] <= 0:
findings.append(
"%s:%d: bubble %r has r=%g — a bubble with no area states no value"
- % (name, line_of(source, match.start()), label, parsed[5])
+ % (name, line, label, parsed[5])
)
continue
accent = bool(ACCENT_RE.search(attrs.get("stroke", "")))
bubbles.append(Bubble(label, parsed[0], parsed[1], parsed[2], parsed[3],
- parsed[4], parsed[5], accent, match.start()))
+ parsed[4], parsed[5], accent, line))
return bubbles
-def check_transforms(source: str, findings: list, name: str) -> None:
- """No transform may move verified geometry or a bound label."""
- spans = transformed_spans(source)
+# === CHECKS ==================================================================
+
- def enclosed(offset):
- return any(start <= offset <= end for start, end in spans)
+def check_transforms(doc: _Scanner, findings: list, name: str) -> None:
+ """No transform may move verified geometry or a bound label.
- def report(offset, what, how):
+ All three carriers are held to that rule - the `transform` attribute, an
+ inline `style="transform: ..."`, and a rule in a <style> block - on the
+ element and on every <g>/<svg> above it, because a gate that closes one of
+ three doorways guards nothing.
+ """
+
+ def report(element, what, how):
findings.append(
"%s:%d: %s carries %s — this checker validates raw cx/cy/r and x/y "
"attributes, so a transform moves the rendered mark away from the "
"number it was checked against. Bake the offset into the coordinates "
- "instead" % (name, line_of(source, offset), what, how)
+ "instead" % (name, element.line, what, how)
)
- for match in CIRCLE_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
- if "data-size" not in attrs:
- continue
- what = "bubble %r" % attrs.get("data-name", "?")
- if "transform" in attrs:
- report(match.start(), what, "transform=%r" % attrs["transform"])
- elif enclosed(match.start()):
- report(match.start(), what, "an ancestor <g>/<svg> transform")
-
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
- if "data-name" not in attrs and "data-tick" not in attrs:
- continue
- what = "a bound label (%s)" % plain(match.group("body"))[:20]
- if "transform" in attrs:
- report(match.start(), what, "transform=%r" % attrs["transform"])
- elif enclosed(match.start()):
- report(match.start(), what, "an ancestor <g>/<svg> transform")
-
- for match in STYLE_RE.finditer(source):
- found = CSS_TRANSFORM_RE.search(match.group("body"))
+ def check_element(element, what):
+ how = transform_carrier(element.attrs)
+ if how is None:
+ how = element.ancestor
+ if how is not None:
+ report(element, what, how)
+
+ for element in doc.circles:
+ if "data-size" in element.attrs:
+ check_element(element, "bubble %r" % element.attrs.get("data-name", "?"))
+
+ for element in doc.texts:
+ if "data-name" in element.attrs or "data-tick" in element.attrs:
+ check_element(element, "a bound label (%s)" % plain(element.body)[:20])
+
+ for element in doc.styles:
+ found = css_moves_mark(element.body)
if found:
findings.append(
- "%s:%d: a CSS `transform` declaration — this checker cannot tell "
+ "%s:%d: a CSS `%s` declaration — this checker cannot tell "
"which marks it applies to, and a transform on verified geometry "
"invalidates every coordinate here. Remove it, or bake the offset "
"into the coordinates"
- % (name, line_of(source, match.start("body") + found.start()))
+ % (name, element.line + element.body.count("\n", 0, found.start("prop")),
+ found.group("prop").lower())
)
-def check_axis(bubbles: list, axis: str, findings: list, source: str,
- name: str):
+def check_axis(bubbles: list, axis: str, findings: list, name: str):
"""One shared linear scale per axis, and no bubble may drift off it.
Returns the (slope, intercept) fit for the axis so the tick check can
@@ -439,7 +630,7 @@ def check_axis(bubbles: list, axis: str, findings: list, source: str,
else:
points = [(b.y, b.cy) for b in bubbles]
drawn_attr = "cy"
- line = line_of(source, bubbles[0].offset)
+ line = bubbles[0].line
slope, intercept = fit(points)
if slope is None:
@@ -464,7 +655,7 @@ def check_axis(bubbles: list, axis: str, findings: list, source: str,
"peers cannot describe a scale to check it against, so its "
"position would define the axis instead of being verified by "
"it. An axis needs two distinct values among the other bubbles"
- % (name, line_of(source, b.offset), b.name, axis, value)
+ % (name, b.line, b.name, axis, value)
)
for index, drawn, expected in outliers(points, RESIDUAL_TOLERANCE):
@@ -473,14 +664,14 @@ def check_axis(bubbles: list, axis: str, findings: list, source: str,
"%s:%d: bubble %r declares %s=%g but draws %s=%g where the shared %s "
"scale its peers describe puts it at %.1f — off by %.1f px. Crowded "
"bubbles are data; never nudge one aside"
- % (name, line_of(source, b.offset), b.name, axis,
+ % (name, b.line, b.name, axis,
points[index][0], drawn_attr, drawn, axis, expected,
abs(drawn - expected))
)
return slope, intercept
-def check_area(bubbles: list, findings: list, source: str, name: str) -> None:
+def check_area(bubbles: list, findings: list, name: str) -> None:
"""r must equal K*sqrt(size) for one K shared by the whole set.
The ratio r^2/size is constant under honest area encoding and varies under
@@ -500,11 +691,11 @@ def check_area(bubbles: list, findings: list, source: str, name: str) -> None:
"scale its peers share puts %.1f — area must be proportional to "
"the value (r = K*sqrt(size)), and radius-proportional sizing "
"shows a 6x value as 36x the ink"
- % (name, line_of(source, b.offset), b.name, b.size, b.r, expected)
+ % (name, b.line, b.name, b.size, b.r, expected)
)
-def check_focal(bubbles: list, findings: list, source: str, name: str) -> None:
+def check_focal(bubbles: list, findings: list, name: str) -> None:
"""At most one bubble wears the accent."""
accented = [b for b in bubbles if b.accent]
for extra in accented[1:]:
@@ -513,11 +704,11 @@ def check_focal(bubbles: list, findings: list, source: str, name: str) -> None:
"max (%r already has it). A second focal mark is a second editorial "
"claim, and the ink ramp exists so everything else stays ranked "
"without spending the accent"
- % (name, line_of(source, extra.offset), extra.name, accented[0].name)
+ % (name, extra.line, extra.name, accented[0].name)
)
-def check_paint_order(bubbles: list, findings: list, source: str, name: str) -> None:
+def check_paint_order(bubbles: list, findings: list, name: str) -> None:
"""Where two bubbles overlap, the larger must be painted first.
Painted later means painted on top: a small bubble under a large one is
@@ -533,33 +724,33 @@ def check_paint_order(bubbles: list, findings: list, source: str, name: str) ->
"%s:%d: bubble %r (r=%g) overlaps %r (r=%g) but is painted "
"first — draw overlapping bubbles largest-first so the small "
"one stays on top and both areas stay readable"
- % (name, line_of(source, a.offset), a.name, a.r, b.name, b.r)
+ % (name, a.line, a.name, a.r, b.name, b.r)
)
-def check_labels(bubbles: list, source: str, findings: list, name: str) -> None:
+def check_labels(bubbles: list, doc: _Scanner, findings: list, name: str) -> None:
"""Bound labels must name a real bubble, match it, and sit on it."""
centres = {b.name: (b.cx, b.cy) for b in bubbles}
seen = set()
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
+ for element in doc.texts:
+ attrs = element.attrs
label = attrs.get("data-name")
if label is None:
continue
- offset = match.start()
- body = plain(match.group("body"))
+ line = element.line
+ body = plain(element.body)
if label not in centres:
findings.append(
"%s:%d: a label names bubble %r, which no circle declares — a "
"label with no mark is not verifiable and reads as data"
- % (name, line_of(source, offset), label)
+ % (name, line, label)
)
continue
if label in seen:
findings.append(
"%s:%d: a second label for bubble %r — one bubble, one label, or "
"the figure states two things about one mark"
- % (name, line_of(source, offset), label)
+ % (name, line, label)
)
continue
seen.add(label)
@@ -569,7 +760,7 @@ def check_labels(bubbles: list, source: str, findings: list, name: str) -> None:
findings.append(
"%s:%d: a label bound to bubble %r reads %r — the visible text "
"and the binding must agree"
- % (name, line_of(source, offset), label, body[:28])
+ % (name, line, label, body[:28])
)
continue
x, y = number(attrs.get("x")), number(attrs.get("y"))
@@ -577,7 +768,7 @@ def check_labels(bubbles: list, source: str, findings: list, name: str) -> None:
findings.append(
"%s:%d: the label for bubble %r has no readable x/y, so its "
"placement cannot be checked"
- % (name, line_of(source, offset), label)
+ % (name, line, label)
)
continue
own_cx, own_cy = centres[label]
@@ -595,23 +786,23 @@ def check_labels(bubbles: list, source: str, findings: list, name: str) -> None:
"%s:%d: the label for bubble %r is drawn at (%g, %g), nearer "
"%r's centre than its own — a label on the wrong bubble "
"renames the mark"
- % (name, line_of(source, offset), label, x, y, nearest)
+ % (name, line, label, x, y, nearest)
)
-def check_ticks(x_fit, y_fit, source: str, findings: list, name: str) -> None:
+def check_ticks(x_fit, y_fit, doc: _Scanner, findings: list, name: str) -> None:
"""Bound axis ticks must print their value and sit on the bubbles' scale."""
ticks = {"x": [], "y": []}
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
+ for element in doc.texts:
+ attrs = element.attrs
axis = attrs.get("data-tick")
if axis is None:
continue
- offset = match.start()
+ line = element.line
if axis not in ("x", "y"):
findings.append(
"%s:%d: a tick label has data-tick=%r, which is neither 'x' nor "
- "'y'" % (name, line_of(source, offset), axis)
+ "'y'" % (name, line, axis)
)
continue
declared = number(attrs.get("data-value"))
@@ -619,48 +810,47 @@ def check_ticks(x_fit, y_fit, source: str, findings: list, name: str) -> None:
findings.append(
"%s:%d: a %s tick has no readable data-value — an unbound axis "
"number is the cheapest way to relabel a whole chart"
- % (name, line_of(source, offset), axis)
+ % (name, line, axis)
)
continue
- body = plain(match.group("body"))
+ body = plain(element.body)
shown, reason = printed_number(body)
if shown is None:
findings.append(
"%s:%d: the %s tick for %g %s (%r) — print one complete number "
- "per tick" % (name, line_of(source, offset), axis, declared,
- reason, body[:28])
+ "per tick" % (name, line, axis, declared, reason, body[:28])
)
continue
if abs(shown - declared) > VALUE_TOLERANCE:
findings.append(
"%s:%d: a %s tick prints %r but declares %g — the label and the "
"binding must state one number"
- % (name, line_of(source, offset), axis, body[:28], declared)
+ % (name, line, axis, body[:28], declared)
)
continue
position = number(attrs.get("x" if axis == "x" else "y"))
if position is None:
findings.append(
"%s:%d: the %s tick for %g has no readable position"
- % (name, line_of(source, offset), axis, declared)
+ % (name, line, axis, declared)
)
continue
- ticks[axis].append((declared, position, offset))
+ ticks[axis].append((declared, position, line))
for axis, fit_pair in (("x", x_fit), ("y", y_fit)):
entries = ticks[axis]
- if len({value for value, _pos, _off in entries}) < 2:
+ if len({value for value, _pos, _line in entries}) < 2:
findings.append(
"%s: the %s axis binds %d distinct tick value(s) — an axis needs "
"at least two bound ticks (data-tick/data-value) or its printed "
"scale is unverifiable against the drawn one"
- % (name, axis, len({v for v, _p, _o in entries}))
+ % (name, axis, len({v for v, _p, _l in entries}))
)
continue
slope, intercept = fit_pair
if slope is None:
continue # already reported by check_axis
- for value, position, offset in entries:
+ for value, position, line in entries:
expected = slope * value + intercept
if abs(position - expected) > TICK_TOLERANCE:
findings.append(
@@ -668,16 +858,37 @@ def check_ticks(x_fit, y_fit, source: str, findings: list, name: str) -> None:
"bubbles themselves describe puts that value at %.1f — the "
"printed axis and the drawn positions disagree, so every "
"reading off this axis is wrong"
- % (name, line_of(source, offset), axis, value, position,
- expected)
+ % (name, line, axis, value, position, expected)
)
+# === DRIVER ==================================================================
+
+
def check_source(path: Path, raw: str) -> list:
"""Findings for one already-read document."""
- source = blank_comments(raw)
findings: list = []
- bubbles = parse_bubbles(source, findings, path.name)
+ doc = parse_document(raw)
+ if doc.error is not None:
+ findings.append(
+ "%s: presents as a bubble chart but could not be parsed as HTML (%s) — "
+ "refusing to report OK on a file this checker could not read"
+ % (path.name, doc.error)
+ )
+ return findings
+ # The raw text claimed a bound <circle> the parser never emitted: an
+ # unclosed quote turned the tag into character data. Nothing downstream
+ # can verify a mark that does not exist, so say which tag was lost rather
+ # than count zero bubbles and leave the author hunting for a circle that
+ # is plainly there.
+ if declares_bubble(raw) and not any("data-size" in e.attrs for e in doc.circles):
+ findings.append(
+ "%s: declares data-size but no complete <circle> could be parsed — an "
+ "unclosed attribute quote swallows the tag; fix the markup. Refusing "
+ "to report OK on a file this checker could not read" % path.name
+ )
+ return findings
+ bubbles = parse_bubbles(doc, findings, path.name)
if len(bubbles) < 4:
findings.append(
@@ -688,14 +899,14 @@ def check_source(path: Path, raw: str) -> list:
)
return findings
- check_transforms(source, findings, path.name)
- x_fit = check_axis(bubbles, "x", findings, source, path.name)
- y_fit = check_axis(bubbles, "y", findings, source, path.name)
- check_area(bubbles, findings, source, path.name)
- check_focal(bubbles, findings, source, path.name)
- check_paint_order(bubbles, findings, source, path.name)
- check_labels(bubbles, source, findings, path.name)
- check_ticks(x_fit, y_fit, source, findings, path.name)
+ check_transforms(doc, findings, path.name)
+ x_fit = check_axis(bubbles, "x", findings, path.name)
+ y_fit = check_axis(bubbles, "y", findings, path.name)
+ check_area(bubbles, findings, path.name)
+ check_focal(bubbles, findings, path.name)
+ check_paint_order(bubbles, findings, path.name)
+ check_labels(bubbles, doc, findings, path.name)
+ check_ticks(x_fit, y_fit, doc, findings, path.name)
return findings
diff --git a/scripts/verify-ridgeline.py b/scripts/verify-ridgeline.py
index d0eb985..f2fda47 100644
--- a/scripts/verify-ridgeline.py
+++ b/scripts/verify-ridgeline.py
@@ -52,6 +52,30 @@ Eight invariants, in the spirit of ADR 0005 and the slopegraph checker:
cannot be read, a missing baseline rule, or a transform anywhere near
verified geometry is a finding, never a skip.
+Markup is read through the stdlib html.parser.HTMLParser, never a regex, so a
+tag is recognized exactly when a browser would recognize it: a quoted `>`
+inside an attribute value does not end the tag, a repeated attribute keeps its
+FIRST value and the rest are not in the document at all, unquoted values and
+upper-case names parse as their canonical form, and a comment's contents are
+never live markup. The regex tag matcher this replaced stopped at the first
+`>` it saw, so `<g data-note=">" transform="translate(0 -80)">` hid its
+transform from the checker while Chromium applied it to every ridge inside -
+the same fail-open shape verify-block-registry.py retired for the same reason.
+
+No transform may move verified geometry or a bound label, and a transform
+reaches the renderer by three carriers: the `transform` attribute, an inline
+`style="..."`, and a rule in a <style> block. All three are refused, on the
+element and on any ancestor <g>/<svg>, following verify-beeswarm.py; the
+property set in CSS_MOVES_MARK_RE is the invariant, adapted to what moves an
+outline (`d`), a baseline rule (`x1`/`y1`/`x2`/`y2`) and a label (`x`/`y`).
+CSS comments are stripped before any carrier is read, as the browser strips
+them: `/**/transform:` is a live declaration, not a quirk.
+
+Scope is read from the raw text with HTML comments removed, BEFORE the parser,
+so a <path> whose broken quoting keeps the parser from emitting it still claims
+the file and is reported rather than skipped - the parser is exactly what an
+unclosed quote defeats.
+
WHAT THIS DOES NOT CHECK, deliberately:
- **What the values mean.** Share, density or count, and how the bins were cut -
@@ -75,33 +99,60 @@ Exit: 0 clean, 1 findings, 2 usage.
from __future__ import annotations
import argparse
-import html
import re
import sys
+from html.parser import HTMLParser
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ASSET_DIR = ROOT / "skills/diagram-design/assets"
-PATH_RE = re.compile(r"<path\b(?P<attrs>[^>]*?)/?>", re.IGNORECASE)
-LINE_RE = re.compile(r"<line\b(?P<attrs>[^>]*?)/?>", re.IGNORECASE)
-TEXT_RE = re.compile(r"<text\b(?P<attrs>[^>]*)>(?P<body>.*?)</text>", re.IGNORECASE | re.DOTALL)
-COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
-NAMED_RE = re.compile(r"<(?P<tag>title|desc)\b[^>]*>(?P<body>.*?)</(?P=tag)>",
- re.IGNORECASE | re.DOTALL)
-GROUP_OPEN_RE = re.compile(r"<(?:g|svg)\b(?P<attrs>[^>]*?)(?P<selfclose>/?)>", re.IGNORECASE)
-GROUP_CLOSE_RE = re.compile(r"</(?:g|svg)\s*>", re.IGNORECASE)
-STYLE_RE = re.compile(r"<style\b[^>]*>(?P<body>.*?)</style>", re.IGNORECASE | re.DOTALL)
-# `transform:` but not `text-transform:` - the editorial template uses the latter.
-CSS_TRANSFORM_RE = re.compile(r"(?<![\w-])transform\s*:", re.IGNORECASE)
-TAG_RE = re.compile(r"<[^>]+>")
-# Both quote styles, for the same reason verify-slopegraph gives: a
-# single-quoted attribute must be read, not silently dropped from the set.
-ATTR_RE = re.compile(
- r"""(?P<name>[\w:-]+)\s*=\s*(?P<quote>["'])(?P<value>.*?)(?P=quote)""",
- re.DOTALL,
+# Every CSS property that can move or reshape a verified mark WITHOUT touching
+# the attributes this checker reads. The enumeration IS the invariant - it is
+# copied from verify-beeswarm.py, where it had already been wrong twice
+# (`transform:` alone missed `style="transform: ..."`, and once that was fixed
+# `style="translate: 80px 0"` walked past it because CSS Transforms Level 2
+# splits the transform into four properties). Three families reach a mark:
+#
+# transform / translate / rotate / scale the four transform properties;
+# the individual three compose WITH `transform`, so each is its own door
+# d / x / y SVG geometry properties. CSS wins
+# over the presentation attribute, so `style="d: path(...)"` on a ridge
+# replaces the very outline that was verified, and x/y do the same to a
+# bound label - a more direct lie than any transform
+# x1 / y1 / x2 / y2 a baseline rule's coordinates. Not
+# geometry properties in any shipping browser, so a declaration naming
+# them is dead today; refused anyway because it costs nothing on honest
+# markup and the alternative is a checker re-hardened the day it stops
+# being dead
+# offset and its path/distance/position/anchor/rotate longhands
+# CSS motion path, which places the element somewhere else entirely
+#
+# Anchored to a declaration start, so `text-transform:` (the editorial skin
+# uses it), `display:` and `--custom:` never match, and the `rotate` inside
+# `transform: rotate(45deg)` is read once as the property and never as the
+# function in its value. A vendor prefix is optional so `-webkit-transform:`
+# is not a free pass.
+CSS_MOVES_MARK_RE = re.compile(
+ r"(?:^|[{;}\n])\s*(?:-(?:webkit|moz|ms|o)-)?"
+ r"(?P<prop>transform|translate|rotate|scale"
+ r"|d|x1|y1|x2|y2|x|y"
+ r"|offset(?:-(?:path|distance|position|anchor|rotate))?)"
+ r"\s*:",
+ re.IGNORECASE,
)
+# A CSS comment is whitespace to the browser, so `/**/transform:` is a live
+# declaration. CSS_MOVES_MARK_RE allows only whitespace between a declaration
+# boundary and the property name, which let a comment sitting there hide the
+# property from it while Chromium applied it. Non-greedy and DOTALL: a comment
+# spans lines, and a stylesheet holds many. See css_moves_mark.
+CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
+# Detection only - deliberately a text search over the raw bytes, HTML comments
+# removed, so a file that so much as mentions the binding in live markup is
+# held to the contract even when the parser cannot read the tag that binds it.
+# See declares_bins.
DECLARES_BINS_RE = re.compile(r"\bdata-bins\s*=", re.IGNORECASE)
+HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
NUM_RE = re.compile(r"[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?")
# Path-data tokens, number branch FIRST so an exponent's `e` is consumed as part
# of its number instead of being read as a command. See parse_d.
@@ -128,31 +179,228 @@ MIN_BINS, MAX_BINS = 8, 40
FOCAL_WIDTH, PLAIN_WIDTH = 2.4, 1.2
ACCENTS = {"#eb6c36", "#f08a59"} # light and dark skin accent tokens
+GROUP_TAGS = ("g", "svg") # the only ancestors whose transform is inherited
+BODY_TAGS = ("text", "title", "desc", "style") # elements whose character data is read
+MARK_TAGS = ("path", "line") # outlines and their baseline rules
+
+
+# === PARSING =================================================================
+
+
+class Element:
+ """One start tag this checker cares about, as the browser tokenized it."""
+
+ __slots__ = ("tag", "attrs", "offset", "line", "body", "ancestor")
+
+ def __init__(self, tag, attrs, offset, line, ancestor):
+ self.tag = tag
+ self.attrs = attrs # first-wins dict, names lower-cased, values unescaped
+ self.offset = offset # offset of `<` in the source, for ordering
+ self.line = line
+ self.body = "" # character data up to the matching end tag
+ self.ancestor = ancestor # how the nearest transformed <g>/<svg> moves it, or None
+
class Ridge:
- __slots__ = ("name", "values", "points", "baseline", "stroke", "width", "offset")
+ __slots__ = ("name", "values", "points", "baseline", "stroke", "width", "line")
- def __init__(self, name, values, points, baseline, stroke, width, offset):
+ def __init__(self, name, values, points, baseline, stroke, width, line):
self.name = name
self.values = values
self.points = points
self.baseline = baseline
self.stroke = stroke
self.width = width
- self.offset = offset
+ self.line = line
@property
def focal(self):
return self.stroke in ACCENTS
+def first_wins(attrs) -> dict:
+ """Attributes as the browser keeps them: on a repeat, the FIRST wins.
+
+ HTML parsing drops a duplicate attribute rather than overwriting the one
+ already on the token, so a second `d` on a path is not merely ignored -
+ it is not in the document at all. A dict comprehension does the opposite,
+ and that gap is a fail-open every caller inherits: a path carrying a
+ dishonest first `d` and an honest second renders the dishonest outline
+ while a last-wins reader checks, and passes, bytes the browser threw away.
+ A present-but-valueless attribute is an empty string, not an absent one.
+ """
+ seen = {}
+ for name, value in attrs:
+ seen.setdefault(name, "" if value is None else value)
+ return seen
+
+
+class _Scanner(HTMLParser):
+ """Collect paths, lines, texts, title/desc and style elements with ancestry.
+
+ HTMLParser already lowercases tag and attribute names, tolerates unquoted
+ values and whitespace around `=`, unescapes entities, keeps a quoted `>`
+ inside the value it belongs to, and never invokes handle_starttag for
+ tag-like text inside a comment or inside <script>/<style> raw text - each
+ of those is exactly a case a regex tag matcher mishandles. Ancestry is
+ tracked for <g>/<svg> only, the elements whose transform a child inherits.
+ """
+
+ def __init__(self, source: str):
+ super().__init__(convert_charrefs=True)
+ self.paths: list = []
+ self.lines: list = []
+ self.texts: list = []
+ self.named: list = [] # <title> and <desc>
+ self.styles: list = []
+ self.error = None
+ self._groups: list = [] # (tag, how) per open <g>/<svg>
+ self._open: list = [] # (tag, Element) per open body element
+ self._line_starts = [0]
+ for index, char in enumerate(source):
+ if char == "\n":
+ self._line_starts.append(index + 1)
+ try:
+ self.feed(source)
+ self.close()
+ except Exception as exc: # noqa: BLE001 - any parser failure fails closed
+ self.error = "%s: %s" % (type(exc).__name__, exc)
+
+ def _offset(self) -> int:
+ line, column = self.getpos()
+ return self._line_starts[line - 1] + column
+
+ def _ancestor(self):
+ for _tag, how in reversed(self._groups):
+ if how is not None:
+ return how
+ return None
+
+ def handle_starttag(self, tag, attrs):
+ self._start(tag, first_wins(attrs), closes=False)
+
+ def handle_startendtag(self, tag, attrs):
+ self._start(tag, first_wins(attrs), closes=True)
+
+ def _start(self, tag, attrs, closes):
+ if tag in GROUP_TAGS:
+ if not closes:
+ how = None
+ if "transform" in attrs:
+ how = "an ancestor <g>/<svg> transform"
+ elif transform_carrier(attrs) is not None:
+ how = "an ancestor <g>/<svg> style transform"
+ self._groups.append((tag, how))
+ return
+ if tag not in MARK_TAGS and tag not in BODY_TAGS:
+ return
+ element = Element(tag, attrs, self._offset(), self.getpos()[0], self._ancestor())
+ if tag == "path":
+ self.paths.append(element)
+ return
+ if tag == "line":
+ self.lines.append(element)
+ return
+ if tag == "text":
+ self.texts.append(element)
+ elif tag == "style":
+ self.styles.append(element)
+ else:
+ self.named.append(element)
+ if not closes:
+ self._open.append((tag, element))
+
+ def handle_endtag(self, tag):
+ stack = self._groups if tag in GROUP_TAGS else self._open if tag in BODY_TAGS else None
+ if stack is None:
+ return
+ # Pop back to the matching open tag - an unclosed inner element ends
+ # with its parent, as it does in the browser's tree.
+ for index in range(len(stack) - 1, -1, -1):
+ if stack[index][0] == tag:
+ del stack[index:]
+ return
+
+ def handle_data(self, data):
+ if self._open:
+ # Innermost only: a <title> tooltip inside a <text> is not part of
+ # the rendered label, and the browser does not draw it either.
+ self._open[-1][1].body += data
+
+
+def parse_document(source: str) -> _Scanner:
+ return _Scanner(source)
+
+
def attrs_of(raw: str) -> dict:
- found = {}
- for match in ATTR_RE.finditer(raw):
- name = match.group("name").lower()
- if name not in found: # a browser keeps the FIRST of a repeat
- found[name] = html.unescape(match.group("value"))
- return found
+ """First-wins attributes of one tag's raw attribute text, via the parser."""
+
+ class _One(HTMLParser):
+ def __init__(self):
+ super().__init__(convert_charrefs=True)
+ self.attrs = {}
+
+ def handle_starttag(self, tag, attrs):
+ self.attrs = first_wins(attrs)
+
+ handle_startendtag = handle_starttag
+
+ scanner = _One()
+ scanner.feed("<x " + raw + ">")
+ scanner.close()
+ return scanner.attrs
+
+
+def transform_carrier(attrs: dict):
+ """How this element carries a transform, phrased for the finding, or None.
+
+ A transform reaches the renderer by three carriers and the `transform`
+ ATTRIBUTE is only the most visible one. Reading the attribute alone lets
+ `style="transform: translateY(...)"` on a ridge, a bound label or an
+ ancestor group move the rendered mark after its raw coordinates were
+ validated. The third carrier, a rule in a <style> block, is reported
+ separately because nothing here can tell which marks such a rule selects.
+ """
+ if "transform" in attrs:
+ return "transform=%r" % attrs["transform"]
+ style = attrs.get("style")
+ if style is not None:
+ found = css_moves_mark(style)
+ if found is not None:
+ return "style=%r (the %s property)" % (style, found.group("prop").lower())
+ return None
+
+
+def css_moves_mark(css: str):
+ """The first mark-moving declaration in CSS text, read past comments, or None.
+
+ Every carrier goes through here - an inline style, an ancestor's inline
+ style, a <style> block - because the browser drops `/* ... */` before it
+ tokenizes, and CSS_MOVES_MARK_RE must see what the browser sees:
+ `style="/**/transform: translateY(8px)"` moved a ridge while the anchored
+ regex walked past the comment. Each comment is blanked to whitespace of
+ the SAME length, newlines kept, so the searched text is aligned with the
+ original character for character: every offset in the returned match is
+ an offset into `css` as written, and a <style> finding that counts
+ newlines up to the property names the right line.
+ """
+ stripped = CSS_COMMENT_RE.sub(
+ lambda found: re.sub(r"[^\n]", " ", found.group()), css)
+ return CSS_MOVES_MARK_RE.search(stripped)
+
+
+def declares_bins(source: str) -> bool:
+ """Does the raw text, HTML comments removed, declare data-bins anywhere?
+
+ Read BEFORE the parser, because the parser is exactly what a broken quote
+ defeats: `<path data-bins="0,1` with no closing quote is character data
+ to HTMLParser, no <path> is ever emitted, and a file whose only ridgeline
+ signal was that tag would otherwise be skipped as out of scope - a
+ fail-open. The raw signal claims the file and check_source then reports
+ the tag the parser could not read. Comments are stripped first so a
+ commented-out draft path does not claim an unrelated file.
+ """
+ return DECLARES_BINS_RE.search(HTML_COMMENT_RE.sub("", source)) is not None
def number(value):
@@ -167,23 +415,12 @@ def number(value):
return None
-def line_of(source: str, offset: int) -> int:
- return source.count("\n", 0, offset) + 1
-
-
def plain(body: str) -> str:
- return TAG_RE.sub("", html.unescape(body)).strip()
-
+ return body.strip()
-def blank_comments(source: str) -> str:
- """Comments replaced with spaces, offsets preserved."""
- return COMMENT_RE.sub(lambda m: " " * len(m.group(0)), source)
-
-def named_text(source: str) -> str:
- return " ".join(
- plain(m.group("body")).lower() for m in NAMED_RE.finditer(source)
- )
+def named_text(doc: _Scanner) -> str:
+ return " ".join(plain(element.body).lower() for element in doc.named)
def median(values):
@@ -198,14 +435,16 @@ def looks_like_ridgeline(path: Path, source: str) -> bool:
"""Does this file present itself as a ridgeline?
Generous on the vocabulary this contract binds: `data-bins` belongs to no
- other chart in this repo, so any file declaring it is held to the contract
- even if nothing else parses - that combination is the fail-closed case.
+ other chart in this repo, so any file declaring it in live markup is held
+ to the contract even if nothing else parses - that combination is the
+ fail-closed case. A declaration inside an HTML comment is not live markup
+ and claims nothing.
"""
if path.name.startswith("example-ridgeline"):
return True
- if DECLARES_BINS_RE.search(source):
+ if declares_bins(source):
return True
- described = named_text(source)
+ described = named_text(parse_document(source))
return any(word in described for word in ("ridgeline", "ridge line", "joyplot"))
@@ -238,30 +477,30 @@ def parse_d(d: str):
return commands, points
-def parse_ridges(source: str, findings: list, name: str) -> list:
+def parse_ridges(doc: _Scanner, findings: list, name: str) -> list:
ridges = []
seen = set()
- for match in PATH_RE.finditer(source):
- raw = match.group("attrs")
- attrs = attrs_of(raw)
+ for element in doc.paths:
+ attrs = element.attrs
+ line = element.line
label = attrs.get("data-ridge")
if label is None:
- # A <path> with no data-ridge is scenery. One whose raw text DOES
- # declare data-bins and still parsed to nothing is markup this
- # checker could not read, which is a finding rather than scenery.
- if DECLARES_BINS_RE.search(raw):
+ # A <path> with no data-ridge is scenery. One that DOES declare
+ # data-bins has claimed to be a distribution and must say whose,
+ # which is a finding rather than scenery.
+ if "data-bins" in attrs:
findings.append(
"%s:%d: a <path> declares data-bins but no data-ridge — a "
"distribution outline must say whose distribution it draws, or "
"its labels cannot be bound to it"
- % (name, line_of(source, match.start()))
+ % (name, line)
)
continue
if label in seen:
findings.append(
"%s:%d: a second path declares data-ridge=%r — one ridge, one "
"outline, or the reader has two shapes and no way to pick"
- % (name, line_of(source, match.start()), label)
+ % (name, line, label)
)
continue
seen.add(label)
@@ -271,21 +510,21 @@ def parse_ridges(source: str, findings: list, name: str) -> list:
"%s:%d: ridge %r declares data-ridge but no data-bins — the declared "
"bins are the basis every drawn vertex is verified against, so an "
"outline without them cannot be checked"
- % (name, line_of(source, match.start()), label)
+ % (name, line, label)
)
continue
values = [number(token) for token in bins_raw.split(",")]
if not values or any(v is None for v in values):
findings.append(
"%s:%d: ridge %r has data-bins=%r, which is not a comma list of "
- "numbers" % (name, line_of(source, match.start()), label, bins_raw)
+ "numbers" % (name, line, label, bins_raw)
)
continue
if any(v < 0 for v in values):
findings.append(
"%s:%d: ridge %r declares a negative bin — a share of requests below "
"zero is not a share, and it would draw below the baseline"
- % (name, line_of(source, match.start()), label)
+ % (name, line, label)
)
continue
baseline = number(attrs.get("data-baseline"))
@@ -294,14 +533,14 @@ def parse_ridges(source: str, findings: list, name: str) -> list:
"%s:%d: ridge %r has no data-baseline — the baseline is the zero of "
"this ridge's amplitude, so an unstated one can be moved to give the "
"ridge headroom and nothing here would notice"
- % (name, line_of(source, match.start()), label)
+ % (name, line, label)
)
continue
commands, points = parse_d(attrs.get("d", ""))
if commands is None or not points:
findings.append(
"%s:%d: ridge %r has a path this checker cannot read — cannot verify "
- "its outline" % (name, line_of(source, match.start()), label)
+ "its outline" % (name, line, label)
)
continue
# Absolute M + L* + Z is the entire permitted grammar. A relative
@@ -317,7 +556,7 @@ def parse_ridges(source: str, findings: list, name: str) -> list:
"coordinate renders against the previous point, so the numbers this "
"checker reads are not where the outline lands. Write the path in "
"absolute M/L/Z commands"
- % (name, line_of(source, match.start()), label, "/".join(commands))
+ % (name, line, label, "/".join(commands))
)
continue
commands = ["Z" if c == "z" else c for c in commands]
@@ -330,7 +569,7 @@ def parse_ridges(source: str, findings: list, name: str) -> list:
"straight segments and closes with Z. A spline through binned counts "
"invents extrema the sample never had, and the source line states the "
"drawing is unsmoothed"
- % (name, line_of(source, match.start()), label, "/".join(commands))
+ % (name, line, label, "/".join(commands))
)
continue
# One command letter per point. SVG lets `L` take repeated coordinate
@@ -343,8 +582,7 @@ def parse_ridges(source: str, findings: list, name: str) -> list:
"contract needs one explicit command per vertex (implicit repetition "
"after an L is legal SVG but leaves the checker pairing commands with "
"the wrong coordinates). Write M, then one L per bin, then Z"
- % (name, line_of(source, match.start()), label,
- len(commands), len(points))
+ % (name, line, label, len(commands), len(points))
)
continue
expected = ["M"] + ["L"] * (len(points) - 1) + ["Z"]
@@ -353,102 +591,78 @@ def parse_ridges(source: str, findings: list, name: str) -> list:
"%s:%d: ridge %r draws %s — the outline opens with one M, walks the "
"bins with L, and closes with a single Z. A second subpath or a "
"mid-path M lifts the pen inside one distribution"
- % (name, line_of(source, match.start()), label, "/".join(commands))
+ % (name, line, label, "/".join(commands))
)
continue
if len(points) != len(values):
findings.append(
"%s:%d: ridge %r declares %d bins but draws %d points — every declared "
"bin needs its vertex and every vertex its bin"
- % (name, line_of(source, match.start()), label, len(values), len(points))
+ % (name, line, label, len(values), len(points))
)
continue
width = number(attrs.get("stroke-width"))
ridges.append(Ridge(label, values, points, baseline,
(attrs.get("stroke") or "").strip().lower(),
- width, match.start()))
+ width, line))
return ridges
-def transformed_spans(source: str) -> list:
- events = []
- for match in GROUP_OPEN_RE.finditer(source):
- if match.group("selfclose"):
- continue
- attrs = attrs_of(match.group("attrs"))
- events.append((match.start(), "open", "transform" in attrs))
- for match in GROUP_CLOSE_RE.finditer(source):
- events.append((match.start(), "close", False))
- events.sort()
- spans, stack = [], []
- for position, kind, transformed in events:
- if kind == "open":
- stack.append((position, transformed))
- elif stack:
- start, was_transformed = stack.pop()
- if was_transformed:
- spans.append((start, position))
- for start, was_transformed in stack:
- if was_transformed:
- spans.append((start, len(source)))
- return spans
-
-
-def check_transforms(source: str, findings: list, name: str) -> None:
- """No transform may move verified geometry or a bound label."""
- spans = transformed_spans(source)
-
- def enclosed(offset):
- return any(start <= offset <= end for start, end in spans)
-
- def report(offset, what, how):
+# === CHECKS ==================================================================
+
+
+def check_transforms(doc: _Scanner, findings: list, name: str) -> None:
+ """No transform may move verified geometry or a bound label.
+
+ All three carriers are held to that rule - the `transform` attribute, an
+ inline `style="transform: ..."`, and a rule in a <style> block - on the
+ element and on every <g>/<svg> above it, because a gate that closes one of
+ three doorways guards nothing.
+ """
+
+ def report(element, what, how):
findings.append(
"%s:%d: %s carries %s — this checker validates raw coordinates, so a "
"transform moves the rendered mark away from the bin it was checked "
"against. Bake the offset into the coordinates instead"
- % (name, line_of(source, offset), what, how)
+ % (name, element.line, what, how)
)
- for pattern, key in ((PATH_RE, "data-ridge"), (LINE_RE, "data-ridge")):
- for match in pattern.finditer(source):
- attrs = attrs_of(match.group("attrs"))
- if key not in attrs:
- continue
- what = "ridge %r" % attrs[key]
- if "transform" in attrs:
- report(match.start(), what, "transform=%r" % attrs["transform"])
- elif enclosed(match.start()):
- report(match.start(), what, "an ancestor <g>/<svg> transform")
-
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
- if "data-ridge" not in attrs and "data-tick" not in attrs:
- continue
- what = "a bound label (%s)" % plain(match.group("body"))[:20]
- if "transform" in attrs:
- report(match.start(), what, "transform=%r" % attrs["transform"])
- elif enclosed(match.start()):
- report(match.start(), what, "an ancestor <g>/<svg> transform")
-
- for match in STYLE_RE.finditer(source):
- found = CSS_TRANSFORM_RE.search(match.group("body"))
+ def check_element(element, what):
+ how = transform_carrier(element.attrs)
+ if how is None:
+ how = element.ancestor
+ if how is not None:
+ report(element, what, how)
+
+ for element in doc.paths + doc.lines:
+ if "data-ridge" in element.attrs:
+ check_element(element, "ridge %r" % element.attrs["data-ridge"])
+
+ for element in doc.texts:
+ if "data-ridge" in element.attrs or "data-tick" in element.attrs:
+ check_element(element, "a bound label (%s)" % plain(element.body)[:20])
+
+ for element in doc.styles:
+ found = css_moves_mark(element.body)
if found:
findings.append(
- "%s:%d: a CSS `transform` declaration — this checker cannot tell "
+ "%s:%d: a CSS `%s` declaration — this checker cannot tell "
"which marks it applies to, and a transform on verified geometry "
"invalidates every coordinate here"
- % (name, line_of(source, match.start("body") + found.start()))
+ % (name, element.line + element.body.count("\n", 0, found.start("prop")),
+ found.group("prop").lower())
)
-def check_bins(ridges: list, findings: list, source: str, name: str) -> bool:
+def check_bins(ridges: list, findings: list, name: str) -> bool:
"""Every ridge samples the same x positions, in increasing order."""
reference = [round(x, 3) for x, _ in ridges[0].points]
if sorted(set(reference)) != reference:
findings.append(
"%s:%d: ridge %r samples x=%s, which is not strictly increasing — bins "
"are ordered, and an x visited twice or out of order redraws the scale"
- % (name, line_of(source, ridges[0].offset), ridges[0].name,
+ % (name, ridges[0].line, ridges[0].name,
"/".join("%g" % x for x in reference[:6]) + "…")
)
return False
@@ -461,13 +675,13 @@ def check_bins(ridges: list, findings: list, source: str, name: str) -> bool:
findings.append(
"%s:%d: ridge %r samples its own x positions — every ridge must share "
"one x-scale or a peak at one x stops meaning one latency"
- % (name, line_of(source, r.offset), r.name)
+ % (name, r.line, r.name)
)
shared = False
return shared
-def check_baselines(ridges: list, source: str, findings: list, name: str):
+def check_baselines(ridges: list, doc: _Scanner, findings: list, name: str):
"""Baselines strictly downward at one pitch, each with its drawn rule.
Returns the derived pitch, or None when the rows could not be read.
@@ -495,8 +709,7 @@ def check_baselines(ridges: list, source: str, findings: list, name: str):
"puts row %d at y=%g — an unevenly pitched stack reads relative "
"amplitude wrong, and a row nudged for headroom is the same lie as a "
"private scale"
- % (name, line_of(source, r.offset), r.name, r.baseline, pitch,
- index + 1, expected)
+ % (name, r.line, r.name, r.baseline, pitch, index + 1, expected)
)
# Each ridge's outline must actually start and end on its own baseline.
@@ -508,14 +721,14 @@ def check_baselines(ridges: list, source: str, findings: list, name: str):
"y=%g, baseline y=%g) — the outline closes along the baseline, so "
"a distribution cut off mid-mass would be drawn as a cliff and "
"read as data"
- % (name, line_of(source, r.offset), r.name, end, y, r.baseline)
+ % (name, r.line, r.name, end, y, r.baseline)
)
for _, y in r.points:
if y - r.baseline > AMPLITUDE_TOLERANCE:
findings.append(
"%s:%d: ridge %r draws a vertex at y=%g, below its own baseline "
"y=%g — a ridge rises from its baseline and never dips through it"
- % (name, line_of(source, r.offset), r.name, y, r.baseline)
+ % (name, r.line, r.name, y, r.baseline)
)
break
@@ -523,8 +736,8 @@ def check_baselines(ridges: list, source: str, findings: list, name: str):
x_first = min(x for x, _ in ridges[0].points)
x_last = max(x for x, _ in ridges[0].points)
rules = {}
- for match in LINE_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
+ for element in doc.lines:
+ attrs = element.attrs
if attrs.get("data-role") != "baseline":
continue
label = attrs.get("data-ridge")
@@ -532,18 +745,18 @@ def check_baselines(ridges: list, source: str, findings: list, name: str):
findings.append(
"%s:%d: a baseline rule declares no data-ridge — an unbound rule can "
"be moved off the row it belongs to and nothing here would notice"
- % (name, line_of(source, match.start()))
+ % (name, element.line)
)
continue
- rules[label] = (attrs, match.start())
+ rules[label] = (attrs, element.offset, element.line)
declared = {r.name: r for r in ridges}
- for label, (attrs, offset) in sorted(rules.items(), key=lambda item: item[1][1]):
+ for label, (attrs, _offset, line) in sorted(rules.items(), key=lambda item: item[1][1]):
if label not in declared:
findings.append(
"%s:%d: a baseline rule names ridge %r, which no path declares — a "
"rule with no ridge reads as a row that is not there"
- % (name, line_of(source, offset), label)
+ % (name, line, label)
)
continue
r = declared[label]
@@ -553,14 +766,14 @@ def check_baselines(ridges: list, source: str, findings: list, name: str):
findings.append(
"%s:%d: the baseline rule for ridge %r is not horizontal — a sloped "
"baseline makes every amplitude on that row a different number"
- % (name, line_of(source, offset), label)
+ % (name, line, label)
)
continue
if abs(y1 - r.baseline) > RULE_TOLERANCE:
findings.append(
"%s:%d: the baseline rule for ridge %r is drawn at y=%g but the ridge "
"declares its baseline at y=%g — the drawn zero and the measured zero "
- "must be one line" % (name, line_of(source, offset), label, y1, r.baseline)
+ "must be one line" % (name, line, label, y1, r.baseline)
)
if rx1 is None or rx2 is None \
or abs(min(rx1, rx2) - x_first) > RULE_TOLERANCE \
@@ -569,7 +782,7 @@ def check_baselines(ridges: list, source: str, findings: list, name: str):
"%s:%d: the baseline rule for ridge %r does not span the bin run "
"(x=%g to x=%g) — a short rule reads as a narrower support than the "
"ridge was sampled over"
- % (name, line_of(source, offset), label, x_first, x_last))
+ % (name, line, label, x_first, x_last))
for r in ridges:
if r.name not in rules:
@@ -577,12 +790,12 @@ def check_baselines(ridges: list, source: str, findings: list, name: str):
"%s:%d: ridge %r has no baseline rule (a <line> with data-ridge and "
"data-role=\"baseline\") — the baseline is where a zero bin sits, and "
"an undrawn one leaves the reader estimating the zero of every "
- "amplitude" % (name, line_of(source, r.offset), r.name)
+ "amplitude" % (name, r.line, r.name)
)
return pitch
-def check_amplitude(ridges: list, findings: list, source: str, name: str) -> None:
+def check_amplitude(ridges: list, findings: list, name: str) -> None:
"""One figure-wide amplitude, derived robustly then enforced exactly."""
# Median of PER-RIDGE medians, not of every vertex pooled. Pooling would let
# one ridge with many nonzero bins outvote several honest ridges with few,
@@ -618,13 +831,12 @@ def check_amplitude(ridges: list, findings: list, source: str, name: str) -> Non
"one amplitude (%.4gpx per unit) puts it at y=%g — a ridge on its "
"own scale wears a silhouette it did not earn, which is the one "
"lie this type is built to tell"
- % (name, line_of(source, r.offset), r.name, value, x, y,
- amplitude, expected)
+ % (name, r.line, r.name, value, x, y, amplitude, expected)
)
break
-def check_overlap(ridges: list, pitch, findings: list, source: str, name: str) -> None:
+def check_overlap(ridges: list, pitch, findings: list, name: str) -> None:
"""Overlap is a feature; a peak hidden behind a peak is not."""
if pitch is None: # the stack could not be read; check_baselines said so
return
@@ -636,11 +848,11 @@ def check_overlap(ridges: list, pitch, findings: list, source: str, name: str) -
"it (pitch %gpx) — overlap is how a ridgeline reads as depth, but a "
"peak reaching that far is occluded by the peaks it passes. Increase "
"the pitch; never shrink one ridge's amplitude to fit"
- % (name, line_of(source, r.offset), r.name, intrusion, pitch)
+ % (name, r.line, r.name, intrusion, pitch)
)
-def check_focus(ridges: list, findings: list, source: str, name: str) -> None:
+def check_focus(ridges: list, findings: list, name: str) -> None:
"""Exactly one accent ridge, with stroke weight agreeing with stroke colour."""
focal = [r for r in ridges if r.focal]
if len(focal) != 1:
@@ -656,13 +868,13 @@ def check_focus(ridges: list, findings: list, source: str, name: str) -> None:
"%s:%d: ridge %r has stroke-width=%s but a %s ridge takes %g — weight "
"is the focus cue that survives greyscale, so a mismatch between "
"colour and weight sends the two cues to different ridges"
- % (name, line_of(source, r.offset), r.name,
+ % (name, r.line, r.name,
"%g" % r.width if r.width is not None else "?",
"focal" if r.focal else "non-focal", want)
)
-def check_ticks(ridges: list, source: str, findings: list, name: str):
+def check_ticks(ridges: list, doc: _Scanner, findings: list, name: str):
"""Bin ticks bound to their printed value, on bin positions, one linear scale.
Returns a callable mapping x to an axis value, or None when the scale could
@@ -671,23 +883,24 @@ def check_ticks(ridges: list, source: str, findings: list, name: str):
"""
bin_xs = [x for x, _ in ridges[0].points]
seen = {}
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
+ for element in doc.texts:
+ attrs = element.attrs
index = attrs.get("data-tick")
if index is None:
continue
- body = plain(match.group("body"))
+ line = element.line
+ body = plain(element.body)
if not index.isdigit():
findings.append(
"%s:%d: a bin tick has data-tick=%r, which is not a tick index"
- % (name, line_of(source, match.start()), index)
+ % (name, line, index)
)
continue
position = int(index)
if position in seen:
findings.append(
"%s:%d: a second tick with data-tick=%r — one tick, one caption"
- % (name, line_of(source, match.start()), index)
+ % (name, line, index)
)
continue
declared = number(attrs.get("data-bin"))
@@ -695,7 +908,7 @@ def check_ticks(ridges: list, source: str, findings: list, name: str):
findings.append(
"%s:%d: the tick reading %r has no data-bin — its visible text is "
"unbound, so it can be exchanged with another tick and nothing here "
- "would notice" % (name, line_of(source, match.start()), body[:20])
+ "would notice" % (name, line, body[:20])
)
continue
printed = number(body)
@@ -703,7 +916,7 @@ def check_ticks(ridges: list, source: str, findings: list, name: str):
findings.append(
"%s:%d: the tick at data-bin=%g prints %r — the visible caption and "
"its binding must state one number"
- % (name, line_of(source, match.start()), declared, body[:20])
+ % (name, line, declared, body[:20])
)
continue
x = number(attrs.get("x"))
@@ -711,11 +924,11 @@ def check_ticks(ridges: list, source: str, findings: list, name: str):
findings.append(
"%s:%d: the tick reading %r is drawn at x=%s, which is not a bin "
"position — a tick off the bins labels a latency the figure never "
- "sampled" % (name, line_of(source, match.start()), body[:20],
+ "sampled" % (name, line, body[:20],
"%g" % x if x is not None else "?")
)
continue
- seen[position] = (x, declared, match.start())
+ seen[position] = (x, declared, line)
if len(seen) < 2:
findings.append(
@@ -733,22 +946,22 @@ def check_ticks(ridges: list, source: str, findings: list, name: str):
)
return None
slope = (vn - v0) / (xn - x0)
- for x, value, offset in ordered:
+ for x, value, line in ordered:
if abs((v0 + slope * (x - x0)) - value) > SCALE_TOLERANCE:
findings.append(
"%s:%d: the tick at x=%g reads %g, off the straight line the other "
"ticks set — a non-linear x-axis makes every printed range a "
- "different distance" % (name, line_of(source, offset), x, value)
+ "different distance" % (name, line, x, value)
)
return None
return lambda x: v0 + slope * (x - x0)
-def check_labels(ridges: list, source: str, findings: list, name: str, scale) -> None:
+def check_labels(ridges: list, doc: _Scanner, findings: list, name: str, scale) -> None:
"""Name and range printed per ridge, bound, agreeing, and on its own row."""
bound = {}
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
+ for element in doc.texts:
+ attrs = element.attrs
label = attrs.get("data-ridge")
if label is None:
continue
@@ -758,25 +971,26 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
findings.append(
"%s:%d: a second %s label for ridge %r — one label per binding, or a "
"reader has two statements and no way to pick"
- % (name, line_of(source, match.start()), role, label)
+ % (name, element.line, role, label)
)
continue
- bound[key] = (plain(match.group("body")), number(attrs.get("y")), match.start())
+ bound[key] = (plain(element.body), number(attrs.get("y")),
+ element.offset, element.line)
declared = {r.name: r for r in ridges}
- for (label, role), (body, y, offset) in sorted(bound.items(),
- key=lambda item: item[1][2]):
+ for (label, role), (body, y, _offset, line) in sorted(bound.items(),
+ key=lambda item: item[1][2]):
if label not in declared:
findings.append(
"%s:%d: a %s label names ridge %r, which no path declares — a label "
"with no mark is not verifiable and reads as data"
- % (name, line_of(source, offset), role, label)
+ % (name, line, role, label)
)
continue
if role not in ("name", "range"):
findings.append(
"%s:%d: a label for ridge %r has data-role=%r, which is neither "
- "'name' nor 'range'" % (name, line_of(source, offset), label, role)
+ "'name' nor 'range'" % (name, line, label, role)
)
continue
r = declared[label]
@@ -792,7 +1006,7 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
"%s:%d: the %s label for ridge %r is drawn at y=%g, nearer "
"%r's baseline than its own — a label on the wrong row renames "
"the distribution"
- % (name, line_of(source, offset), role, label, y, other.name)
+ % (name, line, role, label, y, other.name)
)
break
if role == "name":
@@ -800,7 +1014,7 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
findings.append(
"%s:%d: a name label bound to ridge %r reads %r — the visible name "
"and its binding must agree"
- % (name, line_of(source, offset), label, body)
+ % (name, line, label, body)
)
continue
@@ -809,14 +1023,14 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
findings.append(
"%s:%d: ridge %r prints its range as %r — a range label is two numbers "
"on the x-axis scale, low to high, so the reader can place the mass "
- "without a gridline" % (name, line_of(source, offset), label, body)
+ "without a gridline" % (name, line, label, body)
)
continue
if scale is None:
findings.append(
"%s:%d: ridge %r prints the range %r, which this checker cannot verify "
"because the figure's bin ticks did not read as one scale"
- % (name, line_of(source, offset), label, body)
+ % (name, line, label, body)
)
continue
live = [i for i, v in enumerate(r.values) if v > 0]
@@ -824,7 +1038,7 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
findings.append(
"%s:%d: ridge %r prints a range but declares no nonzero bin — an "
"empty distribution has no range"
- % (name, line_of(source, offset), label)
+ % (name, line, label)
)
continue
want_low = scale(r.points[live[0]][0])
@@ -833,7 +1047,7 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
if low > high:
findings.append(
"%s:%d: ridge %r prints the range %r low end first — %g is above %g"
- % (name, line_of(source, offset), label, body, low, high)
+ % (name, line, label, body, low, high)
)
continue
if abs(low - want_low) > SCALE_TOLERANCE or abs(high - want_high) > SCALE_TOLERANCE:
@@ -842,7 +1056,7 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
"on the figure's own tick scale — a stated range wider than the mass "
"claims support the bins do not show, and a narrower one hides the "
"tail this chart exists to make visible"
- % (name, line_of(source, offset), label, body, want_low, want_high)
+ % (name, line, label, body, want_low, want_high)
)
for r in ridges:
@@ -852,14 +1066,35 @@ def check_labels(ridges: list, source: str, findings: list, name: str, scale) ->
"%s:%d: ridge %r prints no %s label — a ridgeline names each ridge "
"beside its baseline and states the span of its mass, or the "
"reader has a silhouette and no numbers"
- % (name, line_of(source, r.offset), r.name, role)
+ % (name, r.line, r.name, role)
)
+# === DRIVER ==================================================================
+
+
def check_source(path: Path, raw: str) -> list:
- source = blank_comments(raw)
findings: list = []
- ridges = parse_ridges(source, findings, path.name)
+ doc = parse_document(raw)
+ if doc.error is not None:
+ findings.append(
+ "%s: presents as a ridgeline but could not be parsed as HTML (%s) — "
+ "refusing to report OK on a file this checker could not read"
+ % (path.name, doc.error)
+ )
+ return findings
+ # The raw text claimed a bound <path> the parser never emitted: an unclosed
+ # quote turned the tag into character data. Nothing downstream can verify
+ # an outline that does not exist, so say which tag was lost rather than
+ # count zero ridges and leave the author hunting for a path plainly there.
+ if declares_bins(raw) and not any("data-bins" in e.attrs for e in doc.paths):
+ findings.append(
+ "%s: declares data-bins but no complete <path> could be parsed — an "
+ "unclosed attribute quote swallows the tag; fix the markup. Refusing "
+ "to report OK on a file this checker could not read" % path.name
+ )
+ return findings
+ ridges = parse_ridges(doc, findings, path.name)
if len(ridges) < 2:
findings.append(
@@ -891,14 +1126,14 @@ def check_source(path: Path, raw: str) -> list:
% (path.name, bins, MIN_BINS, MAX_BINS, MIN_BINS, MAX_BINS)
)
- check_transforms(source, findings, path.name)
- shared = check_bins(ridges, findings, source, path.name)
- pitch = check_baselines(ridges, source, findings, path.name)
- check_amplitude(ridges, findings, source, path.name)
- check_overlap(ridges, pitch, findings, source, path.name)
- check_focus(ridges, findings, source, path.name)
- scale = check_ticks(ridges, source, findings, path.name) if shared else None
- check_labels(ridges, source, findings, path.name, scale)
+ check_transforms(doc, findings, path.name)
+ shared = check_bins(ridges, findings, path.name)
+ pitch = check_baselines(ridges, doc, findings, path.name)
+ check_amplitude(ridges, findings, path.name)
+ check_overlap(ridges, pitch, findings, path.name)
+ check_focus(ridges, findings, path.name)
+ scale = check_ticks(ridges, doc, findings, path.name) if shared else None
+ check_labels(ridges, doc, findings, path.name, scale)
return findings
diff --git a/scripts/verify-slopegraph.py b/scripts/verify-slopegraph.py
index 163cfc3..475eaee 100644
--- a/scripts/verify-slopegraph.py
+++ b/scripts/verify-slopegraph.py
@@ -22,12 +22,17 @@ Six invariants, each of which has shipped broken in a draft of this type:
numbers. Crowded endpoint labels are data, not a coordinate problem.
3. UNTRANSFORMED GEOMETRY - the coordinates read here are raw attributes, so any
- `transform` on verified geometry, on its labels, or on an ancestor moves the
+ transform on verified geometry, on its labels, or on an ancestor moves the
rendered mark away from the number this checker validated. A single
`transform="translate(0 80)"` on one series line slid its endpoint 80px and
- every check still passed. Transforms are rejected rather than resolved: a
- partial implementation of the SVG transform stack is worse than an honest
- refusal, because it looks like coverage.
+ every check still passed. A transform reaches the renderer by three carriers
+ - the `transform` attribute, an inline `style="..."`, and a rule in a <style>
+ block - and all three are refused, on the element and on any ancestor
+ <g>/<svg>, following verify-beeswarm.py. Transforms are rejected rather than
+ resolved: a partial implementation of the SVG transform stack is worse than
+ an honest refusal, because it looks like coverage. CSS comments are stripped
+ before any carrier is read, as the browser strips them: `/**/transform:` is
+ a live declaration, not a quirk.
4. COMPLETE PRINTED VALUES - the whole visible numeric token must match the
declared one. Matching only the first fragment read the label "512,000" as
@@ -42,7 +47,19 @@ Six invariants, each of which has shipped broken in a draft of this type:
parseable is a finding, never a pass. A checker that reports OK because it
found nothing to compare is the bug, not the gate. `verify-treemap.py`
returned early on `len(cells) < 3` and that is precisely how an undersized
- cell went unverified.
+ cell went unverified. Scope is therefore read twice - from the raw text,
+ HTML comments removed, and through the parser - so a <line> whose broken
+ quoting the parser cannot emit still claims the file and is reported.
+
+Markup is read through the stdlib html.parser.HTMLParser, never a regex, so a
+tag is recognized exactly when a browser would recognize it: a quoted `>`
+inside an attribute value does not end the tag, a repeated attribute keeps its
+FIRST value and the rest are not in the document at all, unquoted values and
+upper-case names parse as their canonical form, and a comment's contents are
+never live markup. The regex tag matcher this replaced stopped at the first
+`>` it saw, so `<g data-note=">" transform="translate(0 -80)">` hid its
+transform from the checker while Chromium applied it to every line inside -
+the same fail-open shape verify-block-registry.py retired for the same reason.
The basis for geometry is the `data-from` / `data-to` pair each series line
declares, never the rendered text. Deriving the basis from text is what let a
@@ -72,27 +89,59 @@ Exit: 0 clean, 1 findings, 2 usage.
from __future__ import annotations
import argparse
-import html
import math
import re
import sys
+from html.parser import HTMLParser
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ASSET_DIR = ROOT / "skills/diagram-design/assets"
-LINE_RE = re.compile(r"<line\b(?P<attrs>[^>]*?)/?>", re.IGNORECASE)
-TEXT_RE = re.compile(r"<text\b(?P<attrs>[^>]*)>(?P<body>.*?)</text>", re.IGNORECASE | re.DOTALL)
-COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
-NAMED_RE = re.compile(r"<(?P<tag>title|desc)\b[^>]*>(?P<body>.*?)</(?P=tag)>",
- re.IGNORECASE | re.DOTALL)
-GROUP_OPEN_RE = re.compile(r"<(?:g|svg)\b(?P<attrs>[^>]*?)(?P<selfclose>/?)>", re.IGNORECASE)
-GROUP_CLOSE_RE = re.compile(r"</(?:g|svg)\s*>", re.IGNORECASE)
-STYLE_RE = re.compile(r"<style\b[^>]*>(?P<body>.*?)</style>", re.IGNORECASE | re.DOTALL)
-# `transform:` but not `text-transform:`. The full-editorial template uses the
-# latter, so an unguarded pattern would report every editorial variant.
-CSS_TRANSFORM_RE = re.compile(r"(?<![\w-])transform\s*:", re.IGNORECASE)
-TAG_RE = re.compile(r"<[^>]+>")
+# Every CSS property that can move or reshape a verified mark WITHOUT touching
+# the attributes this checker reads. The enumeration IS the invariant - it is
+# copied from verify-beeswarm.py, where it had already been wrong twice
+# (`transform:` alone missed `style="transform: ..."`, and once that was fixed
+# `style="translate: 80px 0"` walked past it because CSS Transforms Level 2
+# splits the transform into four properties). Three families reach a mark:
+#
+# transform / translate / rotate / scale the four transform properties;
+# the individual three compose WITH `transform`, so each is its own door
+# x1 / y1 / x2 / y2 / x / y the attributes this checker reads.
+# x and y are SVG geometry properties, and CSS wins over the presentation
+# attribute, so `style="y: 40px"` on a bound label moves it after its raw
+# y was validated. A <line>'s x1/y1/x2/y2 are not geometry properties in
+# any shipping browser, so a declaration naming them is dead today; it is
+# refused anyway because it costs nothing on honest markup and the
+# alternative is a checker that has to be re-hardened the day it stops
+# being dead
+# offset and its path/distance/position/anchor/rotate longhands
+# CSS motion path, which places the element somewhere else entirely
+#
+# Anchored to a declaration start, so `text-transform:` (the editorial skin
+# uses it), `display:` and `--custom:` never match, and the `rotate` inside
+# `transform: rotate(45deg)` is read once as the property and never as the
+# function in its value. A vendor prefix is optional so `-webkit-transform:`
+# is not a free pass.
+CSS_MOVES_MARK_RE = re.compile(
+ r"(?:^|[{;}\n])\s*(?:-(?:webkit|moz|ms|o)-)?"
+ r"(?P<prop>transform|translate|rotate|scale"
+ r"|x1|y1|x2|y2|x|y"
+ r"|offset(?:-(?:path|distance|position|anchor|rotate))?)"
+ r"\s*:",
+ re.IGNORECASE,
+)
+# A CSS comment is whitespace to the browser, so `/**/transform:` is a live
+# declaration. CSS_MOVES_MARK_RE allows only whitespace between a declaration
+# boundary and the property name, which let a comment sitting there hide the
+# property from it while Chromium applied it. Non-greedy and DOTALL: a comment
+# spans lines, and a stylesheet holds many. See css_moves_mark.
+CSS_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
+# Detection only - a raw-text signal read BEFORE the parser, because the parser
+# is exactly what a broken quote defeats (see declares_series). Scoped to a
+# <line> start tag: `data-series` on a <path> is the bump chart's vocabulary.
+DECLARES_SERIES_RE = re.compile(r"<line\b[^>]*\bdata-series\s*=", re.IGNORECASE)
+HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
# The COMPLETE numeric token an author may print: sign, comma-grouped thousands,
# decimals, leading-dot decimals, exponents. Matching only `-?\d+(\.\d+)?` read
# "1e3" as 1 and "512,000" as 512, so a mangled label agreed with its metadata.
@@ -101,23 +150,6 @@ NUMBER_RE = re.compile(
)
DIGIT_RE = re.compile(r"\d")
-# Both quote styles. Matching only double quotes made a single-quoted series
-# line invisible: the detector below sees `data-series` in the raw source either
-# way, but the attribute parser returned nothing, so the line was dropped from
-# the verified set without a word - a file carrying a 400px lie reported clean.
-ATTR_RE = re.compile(
- r"""(?P<name>[\w:-]+)\s*=\s*(?P<quote>["'])(?P<value>.*?)(?P=quote)""",
- re.DOTALL,
-)
-DECLARES_SERIES_RE = re.compile(r"\bdata-series\s*=", re.IGNORECASE)
-# Scope detection to the ELEMENT this contract binds. `data-series` alone is
-# shared vocabulary across the chart variants - a bump chart binds it to
-# <path>, and holding that file to the slopegraph contract rejects a figure
-# for lacking <line> elements it never claimed to have. A slopegraph whose
-# <line> is malformed still matches here, so the fail-closed case is kept.
-LINE_DECLARES_SERIES_RE = re.compile(
- r"<line\b[^>]*?\bdata-series\s*=", re.IGNORECASE | re.DOTALL)
-
# Coordinates ship rounded to one decimal, so a point can sit 0.05px from its
# true position honestly; an author rounding to whole pixels can sit 0.5px off.
# 1.0px clears both and still catches the smallest dishonest nudge worth making
@@ -131,16 +163,37 @@ VALUE_TOLERANCE = 0.001 # printed label vs declared attribute
CAPTION_TOLERANCE = 0.5 # px, state caption x vs the axis it names
ROW_TOLERANCE = 0.5 # px, slack before a label counts as another row
+GROUP_TAGS = ("g", "svg") # the only ancestors whose transform is inherited
+BODY_TAGS = ("text", "title", "desc", "style") # elements whose character data is read
+MARK_TAGS = ("line",) # the element this contract binds
+
+
+# === PARSING =================================================================
+
+
+class Element:
+ """One start tag this checker cares about, as the browser tokenized it."""
+
+ __slots__ = ("tag", "attrs", "offset", "line", "body", "ancestor")
+
+ def __init__(self, tag, attrs, offset, line, ancestor):
+ self.tag = tag
+ self.attrs = attrs # first-wins dict, names lower-cased, values unescaped
+ self.offset = offset # offset of `<` in the source, for ordering
+ self.line = line
+ self.body = "" # character data up to the matching end tag
+ self.ancestor = ancestor # how the nearest transformed <g>/<svg> moves it, or None
+
class Series:
- __slots__ = ("name", "frm", "to", "x1", "y1", "x2", "y2", "offset")
+ __slots__ = ("name", "frm", "to", "x1", "y1", "x2", "y2", "line")
- def __init__(self, name, frm, to, x1, y1, x2, y2, offset):
+ def __init__(self, name, frm, to, x1, y1, x2, y2, line):
self.name = name
self.frm, self.to = frm, to
self.x1, self.y1 = x1, y1
self.x2, self.y2 = x2, y2
- self.offset = offset
+ self.line = line
def value(self, end):
return self.frm if end == "from" else self.to
@@ -152,26 +205,189 @@ class Series:
return self.x1 if end == "from" else self.x2
-def line_of(source: str, offset: int) -> int:
- return source.count("\n", 0, offset) + 1
+def first_wins(attrs) -> dict:
+ """Attributes as the browser keeps them: on a repeat, the FIRST wins.
+
+ HTML parsing drops a duplicate attribute rather than overwriting the one
+ already on the token, so a second `y2` on a line is not merely ignored -
+ it is not in the document at all. A dict comprehension does the opposite,
+ and that gap is a fail-open every caller inherits: a line carrying a
+ dishonest first `y2` and an honest second renders the dishonest endpoint
+ while a last-wins reader checks, and passes, bytes the browser threw away.
+ A present-but-valueless attribute is an empty string, not an absent one.
+ """
+ seen = {}
+ for name, value in attrs:
+ seen.setdefault(name, "" if value is None else value)
+ return seen
-def blank_comments(source: str) -> str:
- """Comments out, length and line numbers preserved.
+class _Scanner(HTMLParser):
+ """Collect lines, texts, title/desc and style elements with ancestry.
- Markup inside a comment is not rendered, so treating it as data reports a
- commented-out old draft as a live defect. Replacing each comment with spaces
- of the same length keeps every later offset and line number honest.
+ HTMLParser already lowercases tag and attribute names, tolerates unquoted
+ values and whitespace around `=`, unescapes entities, keeps a quoted `>`
+ inside the value it belongs to, and never invokes handle_starttag for
+ tag-like text inside a comment or inside <script>/<style> raw text - each
+ of those is exactly a case a regex tag matcher mishandles. Ancestry is
+ tracked for <g>/<svg> only, the elements whose transform a child inherits.
"""
- return COMMENT_RE.sub(lambda m: re.sub(r"[^\n]", " ", m.group(0)), source)
+
+ def __init__(self, source: str):
+ super().__init__(convert_charrefs=True)
+ self.lines: list = []
+ self.texts: list = []
+ self.named: list = [] # <title> and <desc>
+ self.styles: list = []
+ self.error = None
+ self._groups: list = [] # (tag, how) per open <g>/<svg>
+ self._open: list = [] # (tag, Element) per open body element
+ self._line_starts = [0]
+ for index, char in enumerate(source):
+ if char == "\n":
+ self._line_starts.append(index + 1)
+ try:
+ self.feed(source)
+ self.close()
+ except Exception as exc: # noqa: BLE001 - any parser failure fails closed
+ self.error = "%s: %s" % (type(exc).__name__, exc)
+
+ def _offset(self) -> int:
+ line, column = self.getpos()
+ return self._line_starts[line - 1] + column
+
+ def _ancestor(self):
+ for _tag, how in reversed(self._groups):
+ if how is not None:
+ return how
+ return None
+
+ def handle_starttag(self, tag, attrs):
+ self._start(tag, first_wins(attrs), closes=False)
+
+ def handle_startendtag(self, tag, attrs):
+ self._start(tag, first_wins(attrs), closes=True)
+
+ def _start(self, tag, attrs, closes):
+ if tag in GROUP_TAGS:
+ if not closes:
+ how = None
+ if "transform" in attrs:
+ how = "an ancestor <g>/<svg> transform"
+ elif transform_carrier(attrs) is not None:
+ how = "an ancestor <g>/<svg> style transform"
+ self._groups.append((tag, how))
+ return
+ if tag not in MARK_TAGS and tag not in BODY_TAGS:
+ return
+ element = Element(tag, attrs, self._offset(), self.getpos()[0], self._ancestor())
+ if tag == "line":
+ self.lines.append(element)
+ return
+ if tag == "text":
+ self.texts.append(element)
+ elif tag == "style":
+ self.styles.append(element)
+ else:
+ self.named.append(element)
+ if not closes:
+ self._open.append((tag, element))
+
+ def handle_endtag(self, tag):
+ stack = self._groups if tag in GROUP_TAGS else self._open if tag in BODY_TAGS else None
+ if stack is None:
+ return
+ # Pop back to the matching open tag - an unclosed inner element ends
+ # with its parent, as it does in the browser's tree.
+ for index in range(len(stack) - 1, -1, -1):
+ if stack[index][0] == tag:
+ del stack[index:]
+ return
+
+ def handle_data(self, data):
+ if self._open:
+ # Innermost only: a <title> tooltip inside a <text> is not part of
+ # the rendered label, and the browser does not draw it either.
+ self._open[-1][1].body += data
+
+
+def parse_document(source: str) -> _Scanner:
+ return _Scanner(source)
def attrs_of(raw: str) -> dict:
- return {m.group("name"): m.group("value") for m in ATTR_RE.finditer(raw)}
+ """First-wins attributes of one tag's raw attribute text, via the parser."""
+
+ class _One(HTMLParser):
+ def __init__(self):
+ super().__init__(convert_charrefs=True)
+ self.attrs = {}
+
+ def handle_starttag(self, tag, attrs):
+ self.attrs = first_wins(attrs)
+
+ handle_startendtag = handle_starttag
+
+ scanner = _One()
+ scanner.feed("<x " + raw + ">")
+ scanner.close()
+ return scanner.attrs
+
+
+def transform_carrier(attrs: dict):
+ """How this element carries a transform, phrased for the finding, or None.
+
+ A transform reaches the renderer by three carriers and the `transform`
+ ATTRIBUTE is only the most visible one. Reading the attribute alone lets
+ `style="transform: translateY(...)"` on a series line, a bound label or an
+ ancestor group move the rendered mark after its raw coordinates were
+ validated. The third carrier, a rule in a <style> block, is reported
+ separately because nothing here can tell which marks such a rule selects.
+ """
+ if "transform" in attrs:
+ return "transform=%r" % attrs["transform"]
+ style = attrs.get("style")
+ if style is not None:
+ found = css_moves_mark(style)
+ if found is not None:
+ return "style=%r (the %s property)" % (style, found.group("prop").lower())
+ return None
+
+
+def css_moves_mark(css: str):
+ """The first mark-moving declaration in CSS text, read past comments, or None.
+
+ Every carrier goes through here - an inline style, an ancestor's inline
+ style, a <style> block - because the browser drops `/* ... */` before it
+ tokenizes, and CSS_MOVES_MARK_RE must see what the browser sees:
+ `style="/**/transform: translateX(80px)"` moved a mark while the anchored
+ regex walked past the comment. Each comment is blanked to whitespace of
+ the SAME length, newlines kept, so the searched text is aligned with the
+ original character for character: every offset in the returned match is
+ an offset into `css` as written, and a <style> finding that counts
+ newlines up to the property names the right line.
+ """
+ stripped = CSS_COMMENT_RE.sub(
+ lambda found: re.sub(r"[^\n]", " ", found.group()), css)
+ return CSS_MOVES_MARK_RE.search(stripped)
+
+
+def declares_series(source: str) -> bool:
+ """Does the raw text, HTML comments removed, put data-series on a <line>?
+
+ Read BEFORE the parser, because the parser is exactly what a broken quote
+ defeats: `<line data-series="Search` with no closing quote is character
+ data to HTMLParser, no <line> is ever emitted, and a file whose only
+ slopegraph signal was that tag would be skipped as out of scope - a
+ fail-open. The raw signal claims the file and check_source then reports
+ the tag the parser could not read. Comments are stripped first so a
+ commented-out draft line does not claim an unrelated file.
+ """
+ return DECLARES_SERIES_RE.search(HTML_COMMENT_RE.sub("", source)) is not None
def plain(body: str) -> str:
- return html.unescape(TAG_RE.sub("", body)).strip()
+ return body.strip()
def number(value):
@@ -264,9 +480,9 @@ def outliers(points: list, tolerance: float) -> list:
return found
-def named_text(source: str) -> str:
+def named_text(doc: _Scanner) -> str:
"""The accessible name and description, where a figure says what it is."""
- return " ".join(plain(m.group("body")) for m in NAMED_RE.finditer(source)).casefold()
+ return " ".join(plain(element.body) for element in doc.named).casefold()
def looks_like_slopegraph(path: Path, source: str) -> bool:
@@ -277,72 +493,47 @@ def looks_like_slopegraph(path: Path, source: str) -> bool:
declares no parseable series - that combination is the fail-closed case, not
a pass. The whole document is searched: a 4000-character window missed a file
whose only declaration sat behind a long stylesheet.
+
+ Detection is scoped to the ELEMENT this contract binds. `data-series` alone
+ is shared vocabulary across the chart variants - a bump chart binds it to
+ <path>, and holding that file to the slopegraph contract rejects a figure
+ for lacking <line> elements it never claimed to have. Two readings, each
+ covering the other's blind spot: the raw text (comments stripped) claims a
+ <line> whose broken quoting keeps the parser from ever emitting it, and
+ the parser claims a <line> that declares data-series behind a quoted `>`,
+ which the raw scan cannot see past but the browser still draws.
"""
if path.name.startswith("example-slopegraph"):
return True
- if LINE_DECLARES_SERIES_RE.search(source):
+ if declares_series(source):
return True
- described = named_text(source)
+ doc = parse_document(source)
+ if any("data-series" in element.attrs for element in doc.lines):
+ return True
+ described = named_text(doc)
return "slopegraph" in described or "slope graph" in described
-def transformed_spans(source: str) -> list:
- """Offset ranges enclosed by a <g>/<svg> that carries a transform.
-
- Element-level transforms are easy to see; an ancestor's is not, and shifts
- everything inside it identically - which is exactly the change that leaves
- all internal consistency intact while moving every mark on the page.
- """
- events = []
- for match in GROUP_OPEN_RE.finditer(source):
- if match.group("selfclose"):
- continue
- events.append((match.start(), 0, "transform" in attrs_of(match.group("attrs"))))
- for match in GROUP_CLOSE_RE.finditer(source):
- events.append((match.start(), 1, False))
- events.sort()
- stack, spans = [], []
- for position, kind, transformed in events:
- if kind == 0:
- stack.append((position, transformed))
- elif stack:
- start, was_transformed = stack.pop()
- if was_transformed:
- spans.append((start, position))
- # An unclosed transformed group covers everything after it.
- for start, was_transformed in stack:
- if was_transformed:
- spans.append((start, len(source)))
- return spans
-
-
-def parse_series(source: str, findings: list, name: str) -> list:
+def parse_series(doc: _Scanner, findings: list, name: str) -> list:
"""Series lines, with anything unparseable reported rather than dropped."""
series = []
- for match in LINE_RE.finditer(source):
- raw = match.group("attrs")
- attrs = attrs_of(raw)
+ for element in doc.lines:
+ attrs = element.attrs
label = attrs.get("data-series")
if label is None:
# A <line> with no data-series is scenery - an axis rule, a legend
- # swatch - and skipping it is correct. But one whose raw text DOES
- # declare data-series and still parsed to nothing is markup this
- # checker cannot read, and dropping it silently is how a lie ships.
- if DECLARES_SERIES_RE.search(raw):
- findings.append(
- "%s:%d: a <line> declares data-series but its attributes could "
- "not be parsed — the checker will not silently skip markup it "
- "cannot read. Use plain double-quoted attributes"
- % (name, line_of(source, match.start()))
- )
+ # swatch - and skipping it is correct. The parser reads every tag
+ # the browser reads, so there is no "declared but unparseable"
+ # case left to report here.
continue
+ line = element.line
missing = [key for key in ("data-from", "data-to", "x1", "y1", "x2", "y2")
if key not in attrs]
if missing:
findings.append(
"%s:%d: series %r declares data-series but is missing %s — a series "
"line must state both values and both endpoints or it cannot be verified"
- % (name, line_of(source, match.start()), label, ", ".join(missing))
+ % (name, line, label, ", ".join(missing))
)
continue
parsed = [number(attrs[key])
@@ -351,62 +542,63 @@ def parse_series(source: str, findings: list, name: str) -> list:
findings.append(
"%s:%d: series %r has a value or coordinate that is not a finite "
"number — cannot verify its slope"
- % (name, line_of(source, match.start()), label)
+ % (name, line, label)
)
continue
series.append(Series(label, parsed[0], parsed[1], parsed[2], parsed[3],
- parsed[4], parsed[5], match.start()))
+ parsed[4], parsed[5], line))
return series
-def check_transforms(source: str, findings: list, name: str) -> None:
- """No transform may move verified geometry or a bound label."""
- spans = transformed_spans(source)
+# === CHECKS ==================================================================
- def enclosed(offset):
- return any(start <= offset <= end for start, end in spans)
- def report(offset, what, how):
+def check_transforms(doc: _Scanner, findings: list, name: str) -> None:
+ """No transform may move verified geometry or a bound label.
+
+ All three carriers are held to that rule - the `transform` attribute, an
+ inline `style="transform: ..."`, and a rule in a <style> block - on the
+ element and on every <g>/<svg> above it, because a gate that closes one of
+ three doorways guards nothing.
+ """
+
+ def report(element, what, how):
findings.append(
"%s:%d: %s carries %s — this checker validates raw x/y attributes, so "
"a transform moves the rendered mark away from the number it was "
"checked against. Bake the offset into the coordinates instead"
- % (name, line_of(source, offset), what, how)
+ % (name, element.line, what, how)
)
- for match in LINE_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
- if "data-series" not in attrs:
- continue
- what = "series %r" % attrs["data-series"]
- if "transform" in attrs:
- report(match.start(), what, "transform=%r" % attrs["transform"])
- elif enclosed(match.start()):
- report(match.start(), what, "an ancestor <g>/<svg> transform")
-
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
- if "data-series" not in attrs and "data-axis" not in attrs:
- continue
- what = "a bound label (%s)" % plain(match.group("body"))[:20]
- if "transform" in attrs:
- report(match.start(), what, "transform=%r" % attrs["transform"])
- elif enclosed(match.start()):
- report(match.start(), what, "an ancestor <g>/<svg> transform")
-
- for match in STYLE_RE.finditer(source):
- found = CSS_TRANSFORM_RE.search(match.group("body"))
+ def check_element(element, what):
+ how = transform_carrier(element.attrs)
+ if how is None:
+ how = element.ancestor
+ if how is not None:
+ report(element, what, how)
+
+ for element in doc.lines:
+ if "data-series" in element.attrs:
+ check_element(element, "series %r" % element.attrs["data-series"])
+
+ for element in doc.texts:
+ if "data-series" in element.attrs or "data-axis" in element.attrs:
+ check_element(element, "a bound label (%s)" % plain(element.body)[:20])
+
+ for element in doc.styles:
+ found = css_moves_mark(element.body)
if found:
findings.append(
- "%s:%d: a CSS `transform` declaration — this checker cannot tell "
+ "%s:%d: a CSS `%s` declaration — this checker cannot tell "
"which marks it applies to, and a transform on verified geometry "
"invalidates every coordinate here. Remove it, or bake the offset "
"into the coordinates"
- % (name, line_of(source, match.start("body") + found.start()))
+ % (name, element.line + element.body.count("\n", 0, found.start("prop")),
+ found.group("prop").lower())
)
-def check_axes(series: list, findings: list, source: str, name: str) -> None:
+def check_axes(series: list, findings: list, name: str) -> None:
"""Every series must span the same two axis positions."""
for attr, end in (("x1", "from"), ("x2", "to")):
positions = sorted({round(s.axis_x(end), 3) for s in series})
@@ -415,12 +607,12 @@ def check_axes(series: list, findings: list, source: str, name: str) -> None:
findings.append(
"%s:%d: series do not share one %s — found %s (%s). Every line must "
"run between the same two axes or the slopes are not comparable"
- % (name, line_of(source, series[0].offset), attr,
+ % (name, series[0].line, attr,
"/".join("%g" % p for p in positions), offenders)
)
-def check_scale(series: list, findings: list, source: str, name: str) -> None:
+def check_scale(series: list, findings: list, name: str) -> None:
"""The two axes must share one linear value-to-y map, and no point may drift."""
left = [(s.frm, s.y1) for s in series]
right = [(s.to, s.y2) for s in series]
@@ -428,7 +620,7 @@ def check_scale(series: list, findings: list, source: str, name: str) -> None:
values = [v for v, _ in combined]
span = max(values) - min(values)
mid = (max(values) + min(values)) / 2.0
- line = line_of(source, series[0].offset)
+ line = series[0].line
left_fit = fit(left)
right_fit = fit(right)
@@ -478,7 +670,7 @@ def check_scale(series: list, findings: list, source: str, name: str) -> None:
"%s:%d: series %r draws its %s endpoint (%g) at y=%g where the shared "
"scale its peers describe puts %g at y=%.1f — off by %.1f px. Do not move "
"a point to make room for its label"
- % (name, line_of(source, s.offset), s.name, ends[index], value, drawn,
+ % (name, s.line, s.name, ends[index], value, drawn,
value, expected, abs(drawn - expected))
)
@@ -499,11 +691,15 @@ def misplaced_row(series: list, owner: str, end: str, y: float):
return None
-def collect_bound_labels(source: str, findings: list, name: str) -> dict:
- """Bound labels keyed by (series, end, role), with duplicates reported."""
+def collect_bound_labels(doc: _Scanner, findings: list, name: str) -> dict:
+ """Bound labels keyed by (series, end, role), with duplicates reported.
+
+ Each value is (visible text, y, source offset, line); the offset keeps the
+ caller's report order the document's order.
+ """
found = {}
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
+ for element in doc.texts:
+ attrs = element.attrs
label, end = attrs.get("data-series"), attrs.get("data-end")
if label is None or end is None:
continue
@@ -516,33 +712,33 @@ def collect_bound_labels(source: str, findings: list, name: str) -> dict:
findings.append(
"%s:%d: a second %s %s label for series %r — one endpoint, one "
"label, or the figure states two things about one point"
- % (name, line_of(source, match.start()), end, role, label)
+ % (name, element.line, end, role, label)
)
continue
- found[key] = (plain(match.group("body")), number(attrs.get("y")),
- match.start())
+ found[key] = (plain(element.body), number(attrs.get("y")),
+ element.offset, element.line)
return found
-def check_labels(series: list, source: str, findings: list, name: str) -> None:
+def check_labels(series: list, doc: _Scanner, findings: list, name: str) -> None:
"""Printed values and names must exist, be unique, match, and sit on their row."""
- bound = collect_bound_labels(source, findings, name)
+ bound = collect_bound_labels(doc, findings, name)
declared = {s.name for s in series}
- for (label, end, role), (body, y, offset) in sorted(
+ for (label, end, role), (body, y, _offset, line) in sorted(
bound.items(), key=lambda item: item[1][2]
):
if label not in declared:
findings.append(
"%s:%d: a %s label names series %r, which no line declares — a label "
"with no mark is not verifiable and reads as data"
- % (name, line_of(source, offset), role, label)
+ % (name, line, role, label)
)
continue
if end not in ("from", "to"):
findings.append(
"%s:%d: label for series %r has data-end=%r, which is neither "
- "'from' nor 'to'" % (name, line_of(source, offset), label, end)
+ "'from' nor 'to'" % (name, line, label, end)
)
continue
# Row placement. A label bound to one series but drawn beside another's
@@ -555,7 +751,7 @@ def check_labels(series: list, source: str, findings: list, name: str) -> None:
"%s:%d: the %s %s label for series %r is drawn at y=%g, nearer "
"%r's endpoint than its own — a label on the wrong row renames "
"the line"
- % (name, line_of(source, offset), end, role, label, y, sits_by)
+ % (name, line, end, role, label, y, sits_by)
)
for s in series:
@@ -565,24 +761,22 @@ def check_labels(series: list, source: str, findings: list, name: str) -> None:
findings.append(
"%s:%d: series %r prints no %s endpoint value — a slopegraph must "
"label both ends, or the reader has a slope and no magnitude"
- % (name, line_of(source, s.offset), s.name, end)
+ % (name, s.line, s.name, end)
)
else:
- body, _y, offset = value_entry
+ body, _y, _offset, line = value_entry
shown, reason = printed_number(body)
if shown is None:
findings.append(
"%s:%d: the %s endpoint label for %r %s (%r) — label both "
"endpoints with one complete value each"
- % (name, line_of(source, offset), end, s.name, reason,
- body[:28])
+ % (name, line, end, s.name, reason, body[:28])
)
elif abs(shown - s.value(end)) > VALUE_TOLERANCE:
findings.append(
"%s:%d: series %r prints %r at its %s endpoint but declares "
"%g — the label and the geometry must state one number"
- % (name, line_of(source, offset), s.name, body, end,
- s.value(end))
+ % (name, line, s.name, body, end, s.value(end))
)
name_entry = bound.get((s.name, end, "name"))
if name_entry is None:
@@ -590,40 +784,40 @@ def check_labels(series: list, source: str, findings: list, name: str) -> None:
"%s:%d: series %r has no %s name label (data-role=\"name\") — a "
"slopegraph names every series at both ends, and an unbound name "
"can be swapped with another row undetected"
- % (name, line_of(source, s.offset), s.name, end)
+ % (name, s.line, s.name, end)
)
continue
- body, _y, offset = name_entry
+ body, _y, _offset, line = name_entry
if body != s.name:
findings.append(
"%s:%d: a name label bound to series %r reads %r — the visible "
"name and the binding must agree"
- % (name, line_of(source, offset), s.name, body[:28])
+ % (name, line, s.name, body[:28])
)
-def check_captions(series: list, source: str, findings: list, name: str) -> None:
+def check_captions(series: list, doc: _Scanner, findings: list, name: str) -> None:
"""Each state caption must name the axis it is drawn against."""
seen = {}
- for match in TEXT_RE.finditer(source):
- attrs = attrs_of(match.group("attrs"))
+ for element in doc.texts:
+ attrs = element.attrs
end = attrs.get("data-axis")
if end is None:
continue
if end not in ("from", "to"):
findings.append(
"%s:%d: a state caption has data-axis=%r, which is neither 'from' "
- "nor 'to'" % (name, line_of(source, match.start()), end)
+ "nor 'to'" % (name, element.line, end)
)
continue
if end in seen:
findings.append(
"%s:%d: a second %r state caption — one axis, one caption"
- % (name, line_of(source, match.start()), end)
+ % (name, element.line, end)
)
continue
- seen[end] = (number(attrs.get("x")), plain(match.group("body")),
- attrs.get("data-state"), match.start())
+ seen[end] = (number(attrs.get("x")), plain(element.body),
+ attrs.get("data-state"), element.line)
for end in ("from", "to"):
if end not in seen:
@@ -633,14 +827,14 @@ def check_captions(series: list, source: str, findings: list, name: str) -> None
% (name, end, end)
)
continue
- x, body, declared, offset = seen[end]
+ x, body, declared, line = seen[end]
expected = series[0].axis_x(end)
if x is None or abs(x - expected) > CAPTION_TOLERANCE:
findings.append(
"%s:%d: the %r state caption (%r) is drawn at x=%s but its axis is at "
"x=%g — the captions are swapped or misplaced, which reverses the "
"direction every slope is read in"
- % (name, line_of(source, offset), end, body[:20],
+ % (name, line, end, body[:20],
"%g" % x if x is not None else "?", expected)
)
# Position alone is not enough: swapping just the two visible strings
@@ -651,13 +845,13 @@ def check_captions(series: list, source: str, findings: list, name: str) -> None
"%s:%d: the %r state caption (%r) has no data-state — its visible "
"text is unbound, so it can be exchanged with the other caption and "
"nothing here would notice"
- % (name, line_of(source, offset), end, body[:20])
+ % (name, line, end, body[:20])
)
elif body != declared:
findings.append(
"%s:%d: the %r state caption reads %r but declares data-state=%r — the "
"visible caption and its binding must agree"
- % (name, line_of(source, offset), end, body[:20], declared)
+ % (name, line, end, body[:20], declared)
)
if len(seen) == 2:
@@ -666,15 +860,36 @@ def check_captions(series: list, source: str, findings: list, name: str) -> None
findings.append(
"%s:%d: both state captions read %r — two states the reader cannot "
"tell apart is not a comparison"
- % (name, line_of(source, second[3]), first[1])
+ % (name, second[3], first[1])
)
+# === DRIVER ==================================================================
+
+
def check_source(path: Path, raw: str) -> list:
"""Findings for one already-read document."""
- source = blank_comments(raw)
findings: list = []
- series = parse_series(source, findings, path.name)
+ doc = parse_document(raw)
+ if doc.error is not None:
+ findings.append(
+ "%s: presents as a slopegraph but could not be parsed as HTML (%s) — "
+ "refusing to report OK on a file this checker could not read"
+ % (path.name, doc.error)
+ )
+ return findings
+ # The raw text claimed a bound <line> the parser never emitted: an unclosed
+ # quote turned the tag into character data. Nothing downstream can verify
+ # a mark that does not exist, so say which tag was lost rather than count
+ # zero series and leave the author hunting for a line that is plainly there.
+ if declares_series(raw) and not any("data-series" in e.attrs for e in doc.lines):
+ findings.append(
+ "%s: declares data-series on a <line> but no complete <line> could be "
+ "parsed — an unclosed attribute quote swallows the tag; fix the markup. "
+ "Refusing to report OK on a file this checker could not read" % path.name
+ )
+ return findings
+ series = parse_series(doc, findings, path.name)
if len(series) < 2:
findings.append(
@@ -684,11 +899,11 @@ def check_source(path: Path, raw: str) -> list:
)
return findings
- check_transforms(source, findings, path.name)
- check_axes(series, findings, source, path.name)
- check_scale(series, findings, source, path.name)
- check_labels(series, source, findings, path.name)
- check_captions(series, source, findings, path.name)
+ check_transforms(doc, findings, path.name)
+ check_axes(series, findings, path.name)
+ check_scale(series, findings, path.name)
+ check_labels(series, doc, findings, path.name)
+ check_captions(series, doc, findings, path.name)
return findings