From ea69cb1407eb320af1d0cab659ac5b87a32ebc40 Mon Sep 17 00:00:00 2001 From: felix Date: Mon, 23 Nov 2026 03:42:47 +0000 Subject: [PATCH 1/3] =?UTF-8?q?feat(id-render):=20assertion=20half=20of=20?= =?UTF-8?q?stage=202=20=E2=80=94=20consume=20the=20#5850=20vocabulary=20(#?= =?UTF-8?q?12836)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The #5855 assumption A2 deferral is discharged now #5850 is settled: the assertion vocabulary lands as versioned data (src/assertion_vocabulary.rs, transcribed from the #5850 decision record), stage 2 validates the assert slot against it (unknown dimension/token fails with suggestions in the #5849 idiom; raw values rejected per #5850 invariant 1; a dimension asserted twice in one slot is an error per #5854 §2.2; the slot does not apply to raw regions per #5849 §3.1), and stage 3 composes the slot's assertions at instance specificity alongside the caller-supplied data. Lowering honours them through the existing per-target tables; the GUI report now accounts for every resolved assertion by disposition under the presentation decision (#5854 §2.1 layer 4). Stale crate docs corrected (lib.rs and the Cargo.toml header no longer claim first stages or an unsettled #5850). Tests: tests/assertions.rs, 12 tests naming the decision-record behaviours they verify, including the assertion-bearing worked example lowered on all three targets. --- pkgs/id/crates/id-render/Cargo.toml | 18 +- .../id-render/src/assertion_vocabulary.rs | 302 ++++++++++++++ pkgs/id/crates/id-render/src/compose.rs | 54 ++- pkgs/id/crates/id-render/src/lib.rs | 44 +- pkgs/id/crates/id-render/src/lower.rs | 7 +- pkgs/id/crates/id-render/src/lower_gui.rs | 81 +++- pkgs/id/crates/id-render/src/lower_native.rs | 6 +- pkgs/id/crates/id-render/src/validate.rs | 54 ++- pkgs/id/crates/id-render/tests/assertions.rs | 375 ++++++++++++++++++ 9 files changed, 898 insertions(+), 43 deletions(-) create mode 100644 pkgs/id/crates/id-render/src/assertion_vocabulary.rs create mode 100644 pkgs/id/crates/id-render/tests/assertions.rs diff --git a/pkgs/id/crates/id-render/Cargo.toml b/pkgs/id/crates/id-render/Cargo.toml index d939e0399b..e720387904 100644 --- a/pkgs/id/crates/id-render/Cargo.toml +++ b/pkgs/id/crates/id-render/Cargo.toml @@ -8,15 +8,15 @@ license = "MIT OR Apache-2.0" # Compiler core for the rendering pipeline settled in decision record # #5855 (doc/2026-11-08_decision_id5855_rendering_pipeline_conformance.md), -# implementation follow-up #7918. This crate implements stages 1-3 -# (parse, the vocabulary half of validate, compose) and stages 4-5 -# (lower, emit) for the web target. The vocabularies and mapping -# tables are consumed as data (src/vocabulary.rs, src/web_table.rs), -# never as pipeline code branches (#5855 invariant 6). The assertion -# half of validation consumes the #5850 assertion vocabulary; #5850 -# is not settled yet, so the `assert` slot is carried opaquely until -# it lands. Native (#5852) and custom-GUI (#5853) lowering are -# follow-on work on #7918. +# implementation follow-up #7918. This crate implements all five +# stages — parse, validate, compose, and lower + emit for the web +# (#5851), native (#5852), and custom-GUI (#5853) targets. The +# vocabularies and mapping tables are consumed as data +# (src/vocabulary.rs, src/assertion_vocabulary.rs, src/web_table.rs, +# src/native_table.rs, src/gui_table.rs), never as pipeline code +# branches (#5855 invariant 6). The assertion half of validation +# consumes the #5850 assertion vocabulary, settled and consumed as +# versioned data (the #5855 assumption A2 deferral is discharged). [dependencies] diff --git a/pkgs/id/crates/id-render/src/assertion_vocabulary.rs b/pkgs/id/crates/id-render/src/assertion_vocabulary.rs new file mode 100644 index 0000000000..4c960bc7bb --- /dev/null +++ b/pkgs/id/crates/id-render/src/assertion_vocabulary.rs @@ -0,0 +1,302 @@ +//! The style assertion vocabulary v1, as data. +//! +//! Every entry is transcribed from the decision record on issue +//! #5850 ("style assertion vocabulary v1", decided 2026-11-08, +//! comment 6719140810; the issue is closed and the record is the +//! settled vocabulary): the closed dimension set of §2, the colour +//! roles of §3, the typography roles of §4, and the spacing, +//! density, corner, and elevation roles of §6. The emphasis values +//! are the variant roles the parent design names (primary, +//! destructive, subtle — #5679's style-vocabulary line, exercised +//! in #5850 §2's examples and mapped by #5851 §3.5 / #5852 §3.4). +//! +//! Per #5855 invariant 6 ("tables are data"), a vocabulary change +//! is a change to this table, never a change to validator or +//! pipeline code. This module is the discharge of #5855 assumption +//! A2: stage 2 was defined to carry the `assert` slot opaquely +//! until #5850 settled; it has settled, so the slot is now parsed +//! and validated against this data (see [`crate::validate`]) and +//! composed as layer-3 assertions (see [`crate::compose`]). +//! +//! The slot grammar, transcribing #5850 §2's model (an assertion +//! is a (dimension, role-value) pair): the `assert` value is a +//! comma-separated list of `dimension token` pairs, e.g. +//! `assert="tone accent, emphasis primary"`. Whitespace around a +//! pair is insignificant. A dimension may appear at most once per +//! slot — an exact tie between two assertions in the source is an +//! authoring error, never resolved by order (#5854 §2.2). +//! +//! Deliberately not in the grammar: state-qualified assertions. +//! #5850 §5 fixes states as deltas the target derives from the +//! base roles, with a fixed precedence; authors never assert +//! per-state styling directly. The state roles themselves +//! (hover, focus-visible, active, selected, disabled, error, +//! loading) are consumed by the targets' state machinery (see +//! [`crate::gui_table`]), not by this slot. + +/// The version of the assertion vocabulary this table transcribes +/// (#5850: "style assertion vocabulary v1"). A vocabulary version +/// change re-issues this table (#5850 invariant 2: the dimension +/// set is closed in v1; extension is by version change, never by +/// per-program custom dimensions). +pub const ASSERTION_VOCABULARY_VERSION: &str = "1"; + +/// One assertion dimension of #5850 §2 with its closed role +/// domain. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DimensionSpec { + /// Dimension name, e.g. `tone`. + pub name: &'static str, + /// One-line purpose, used in error messages. + pub purpose: &'static str, + /// The #5850 section that settles this dimension's domain. + pub section: &'static str, + /// The closed set of role tokens the dimension accepts in v1. + pub tokens: &'static [&'static str], +} + +/// The spacing role keys of #5850 §6 (`space-0`…`space-8`), +/// shared by the `gap` and `pad` dimensions. +pub const SPACING_TOKENS: &[&str] = &[ + "space-0", "space-1", "space-2", "space-3", "space-4", "space-5", "space-6", "space-7", + "space-8", +]; + +/// The full v1 dimension set: #5850 §2's closed list, in the +/// record's order. +pub const DIMENSIONS: &[DimensionSpec] = &[ + DimensionSpec { + name: "tone", + purpose: "Which colour role applies", + section: "§3", + tokens: &[ + // §3 surface roles. + "surface-base", + "surface-raised", + "surface-sunken", + "surface-overlay", + "surface-inverse", + // §3 content roles. + "content-primary", + "content-secondary", + "content-muted", + "content-inverse", + "content-link", + // §3 accent/identity roles. + "accent", + "accent-content", + // §3 status roles. + "success", + "warning", + "danger", + "info", + // §3 border roles. + "border-subtle", + "border-strong", + "border-focus", + ], + }, + DimensionSpec { + name: "emphasis", + purpose: "Variant emphasis of the element", + section: "§2", + tokens: &["primary", "destructive", "subtle"], + }, + DimensionSpec { + name: "density", + purpose: "Spacing/control density", + section: "§6", + tokens: &["comfortable", "compact"], + }, + DimensionSpec { + name: "text", + purpose: "Typography role", + section: "§4", + tokens: &[ + "display", + "heading", + "body", + "body-small", + "caption", + "label", + "code", + "link", + ], + }, + DimensionSpec { + name: "gap", + purpose: "Spacing role between children", + section: "§6", + tokens: SPACING_TOKENS, + }, + DimensionSpec { + name: "pad", + purpose: "Spacing role inside the element", + section: "§6", + tokens: SPACING_TOKENS, + }, + DimensionSpec { + name: "corner", + purpose: "Corner shape role", + section: "§6", + tokens: &["corner-square", "corner-rounded", "corner-full"], + }, + DimensionSpec { + name: "elevation", + purpose: "Elevation (ordering) role", + section: "§6", + tokens: &[ + "elevation-flat", + "elevation-raised", + "elevation-overlay", + ], + }, +]; + +/// Looks up a dimension by name. +#[must_use] +pub fn lookup_dimension(name: &str) -> Option<&'static DimensionSpec> { + DIMENSIONS.iter().find(|spec| spec.name == name) +} + +/// One parsed assertion from an `assert` slot: a (dimension, +/// role-value) pair (#5850 §2). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SlotAssertion { + /// Dimension name (a member of [`DIMENSIONS`]). + pub dimension: String, + /// Role token (a member of the dimension's domain). + pub token: String, +} + +/// Whether `word` has the shape of a role name: a lowercase ASCII +/// letter followed by lowercase letters, digits, and hyphens (the +/// shape of every name in the #5849/#5850 vocabularies). A word +/// without this shape in the token position is a raw value — a +/// hex colour, a size, a font name — which #5850 invariant 1 +/// forbids in assertions. +fn is_role_name(word: &str) -> bool { + let mut chars = word.chars(); + match chars.next() { + Some(c) if c.is_ascii_lowercase() => {} + _ => return false, + } + chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-') +} + +/// Up to three names from `names` nearest to `unknown`, for +/// suggestion lists — the #5849 §3.2 idiom, with the same +/// deliberately simple heuristic as +/// [`crate::vocabulary::nearest_names`]: shared prefix first, +/// then shared first letter, in table order. +fn nearest<'a>(unknown: &str, names: &[&'a str]) -> Vec<&'a str> { + let first = unknown.chars().next(); + let mut out: Vec<&'a str> = Vec::new(); + for name in names { + if name.starts_with(unknown) || unknown.starts_with(name) { + out.push(name); + } + } + for name in names { + if out.len() >= 3 { + break; + } + if name.chars().next() == first && !out.contains(name) { + out.push(name); + } + } + out.truncate(3); + out +} + +/// The dimension names, for error messages. +fn dimension_names() -> Vec<&'static str> { + DIMENSIONS.iter().map(|d| d.name).collect() +} + +/// Parses and validates one `assert` slot value against the +/// vocabulary: the grammar above, the closed dimension set, each +/// dimension's closed token domain, the no-raw-values rule +/// (#5850 invariant 1), and the one-pair-per-dimension rule +/// (#5854 §2.2). Returns the parsed pairs, or every problem +/// found as a message string — the callers (stage 2 validation, +/// stage 3 composition) attach the element's source location, +/// exactly as for the #5849 attribute checks. +pub fn parse_assert_slot(value: &str) -> Result, Vec> { + let mut problems: Vec = Vec::new(); + let mut assertions: Vec = Vec::new(); + if value.trim().is_empty() { + problems.push( + "the `assert` slot is empty: it names dimension/token pairs \ + (e.g. `tone accent, emphasis primary`) or is omitted (#5850 §2)" + .to_string(), + ); + return Err(problems); + } + for chunk in value.split(',') { + let chunk = chunk.trim(); + let words: Vec<&str> = chunk.split_whitespace().collect(); + if words.len() != 2 { + problems.push(format!( + "`assert` entry `{chunk}` is not a dimension/token pair: an assertion \ + is a (dimension, role-value) pair, e.g. `tone accent` (#5850 §2)" + )); + continue; + } + let (dimension, token) = (words[0], words[1]); + let Some(spec) = lookup_dimension(dimension) else { + let suggestions = nearest(dimension, &dimension_names()); + let hint = if suggestions.is_empty() { + String::new() + } else { + format!("; nearest dimensions: {}", suggestions.join(", ")) + }; + problems.push(format!( + "unknown assertion dimension `{dimension}` in `assert`: the v1 dimensions \ + are [{}]{hint} (#5850 §2)", + dimension_names().join(", ") + )); + continue; + }; + if !is_role_name(token) { + problems.push(format!( + "`assert` token `{token}` is not a role name: assertions name roles, \ + never raw values — no hex colours, sizes, font names, or target \ + class names (#5850 invariant 1)" + )); + continue; + } + if !spec.tokens.contains(&token) { + let suggestions = nearest(token, spec.tokens); + let hint = if suggestions.is_empty() { + String::new() + } else { + format!("; nearest roles: {}", suggestions.join(", ")) + }; + problems.push(format!( + "unknown assertion token `{token}` for dimension `{dimension}` in \ + `assert`: the {dimension} roles are [{}]{hint} (#5850 {})", + spec.tokens.join(", "), + spec.section + )); + continue; + } + if assertions.iter().any(|a| a.dimension == dimension) { + problems.push(format!( + "dimension `{dimension}` is asserted twice in one `assert` slot: an \ + exact tie between two assertions in the source is an authoring \ + error, never resolved by order (#5854 §2.2)" + )); + continue; + } + assertions.push(SlotAssertion { + dimension: dimension.to_string(), + token: token.to_string(), + }); + } + if problems.is_empty() { + Ok(assertions) + } else { + Err(problems) + } +} diff --git a/pkgs/id/crates/id-render/src/compose.rs b/pkgs/id/crates/id-render/src/compose.rs index a5c4ca3ee6..1ed0230682 100644 --- a/pkgs/id/crates/id-render/src/compose.rs +++ b/pkgs/id/crates/id-render/src/compose.rs @@ -22,14 +22,18 @@ //! style overrides, then presentation overrides per #5853) → //! raw CSS (layer 5, web target only). //! -//! Everything the cascade consumes beyond the validated IR is -//! *data* supplied by the caller ([`ComposeData`]): the assertion -//! sets (the `assert` slot's grammar is #5850's and is still -//! carried opaquely by stages 1–2, per #5855 assumption A2), the +//! Layer 3 has two inputs. The first is the source itself: each +//! element's `assert` slot, validated against the #5850 +//! vocabulary by stage 2, enters as assertions at instance +//! specificity — the slot binds to this element instance in the +//! one source (#5854 §2.2). The second is *data* supplied by the +//! caller ([`ComposeData`]): further assertion sets, the //! override map, and the theme tables. Elements are addressed by //! their document path (see [`element_path`]), a deterministic //! address derived from the IR itself — no source syntax is -//! invented for bindings. +//! invented for bindings. (#5855 assumption A2 carried the slot +//! opaquely until #5850 settled; the record has settled and the +//! deferral is discharged.) //! //! The output is the resolved IR for the one target //! ([`ComposedDocument`]): every element carries its final @@ -51,6 +55,7 @@ use std::collections::{BTreeMap, BTreeSet}; +use crate::assertion_vocabulary; use crate::{BuildError, Document, Element, Node, RawRegion, Span}; /// The facts about one target that composition may consult: the @@ -487,12 +492,49 @@ impl ComposeCx<'_> { self.element_paths.insert(path.to_string()); let mut by_property: BTreeMap = BTreeMap::new(); - // Layer 3: assertions for this element. + // Layer 3: assertions for this element — the element's + // own `assert` slot at instance specificity, plus the + // caller-supplied data assertions bound to this path. + // The slot was validated by stage 2; a document that + // reaches compose unvalidated and carries a bad slot + // fails here with the same located errors rather than + // silently dropping the assertions. + let mut source_assertions: Vec = Vec::new(); + if el.has_attr("assert") { + match el.attr("assert") { + Some(value) => match assertion_vocabulary::parse_assert_slot(value) { + Ok(pairs) => { + source_assertions.extend(pairs.into_iter().map(|pair| { + AssertionInput { + element_path: path.to_string(), + property: pair.dimension, + token: pair.token, + specificity: Specificity::Instance, + } + })); + } + Err(problems) => { + for problem in problems { + self.errors + .push(BuildError::new(problem, el.span.line, el.span.col)); + } + } + }, + None => { + self.errors.push(BuildError::new( + format!("attribute `assert` on <{}> requires a value", el.name), + el.span.line, + el.span.col, + )); + } + } + } let assertions: Vec<&AssertionInput> = self .data .assertions .iter() .filter(|a| a.element_path == path) + .chain(source_assertions.iter()) .collect(); let mut properties: BTreeSet = BTreeSet::new(); for a in &assertions { diff --git a/pkgs/id/crates/id-render/src/lib.rs b/pkgs/id/crates/id-render/src/lib.rs index 5c04bf1dee..8f8eaf5fd4 100644 --- a/pkgs/id/crates/id-render/src/lib.rs +++ b/pkgs/id/crates/id-render/src/lib.rs @@ -7,23 +7,31 @@ //! #5851/#5852/#5853 consumed as data inputs to lowering, never as code //! branches in the pipeline. //! -//! This crate implements the first stages: +//! This crate implements all five stages: //! //! * **Stage 1 — parse** ([`parse`]): semantic source in the HTML-shaped //! authoring syntax of decision record #5849 §2 parses to the IR //! ([`Document`]). Parse errors are fatal, located, and never recovered //! by guessing (#5855 §2.1). -//! * **Stage 2 — validate, vocabulary half** ([`validate`]): the IR is +//! * **Stage 2 — validate** ([`validate`]): the IR is //! checked against the #5849 element vocabulary (consumed as data from //! [`vocabulary`]): unknown element kinds, unknown attributes, missing //! required attributes, enum-valued attribute domains, the child and //! sibling rules of #5849 §4.5, and the names-not-expressions rule for //! binding slots (#5849 §8) are build errors with source locations. +//! The assertion half of the stage checks the `assert` slot against +//! the #5850 assertion vocabulary (consumed as versioned data from +//! [`assertion_vocabulary`]): an unknown dimension or role token +//! fails with suggestions (the #5849 idiom), a raw value is rejected +//! (#5850 invariant 1), and a dimension asserted twice in one slot +//! is an error (#5854 §2.2). //! //! * **Stage 3 — compose** ([`compose`]): the #5854 cascade over -//! data-supplied composition tables (theme layering, assertion and -//! override resolution, the web-only raw-CSS layer), producing the -//! resolved IR and composition report for one target. Conditional +//! the source `assert` slots (layer-3 assertions at instance +//! specificity) and data-supplied composition tables (theme +//! layering, further assertion and override resolution, the +//! web-only raw-CSS layer), producing the resolved IR and +//! composition report for one target. Conditional //! blocks await a #5849 vocabulary representation; see the module //! documentation for the stated boundary. //! @@ -57,13 +65,20 @@ //! renderer registration (§2.2) are build-time errors, never //! runtime gaps. //! -//! The assertion half of stage 2 is deliberately not implemented yet: -//! the `assert` attribute's grammar and role vocabulary are #5850's, -//! and #5850 is not settled. The slot is parsed and carried opaquely, -//! exactly as #5855 assumption A2 prescribes (the pipeline is defined -//! over element kinds and assertion roles generically and consumes -//! both vocabularies as versioned data). +//! The assertion half of stage 2 was the one deferral #5855 +//! assumption A2 prescribed: the `assert` attribute's grammar and +//! role vocabulary are #5850's, and the slot was carried opaquely +//! until that record settled. #5850 is settled (its decision +//! record is the vocabulary v1 on the closed issue), so the +//! deferral is discharged: [`assertion_vocabulary`] consumes the +//! record as versioned data, stage 2 validates the slot against +//! it, and stage 3 composes the slot's assertions like any other +//! layer-3 input. What remains outside the pipeline is unchanged +//! and belongs to its own records: state-delta composition +//! (#5851 §3.6 — targets render state behaviour natively) and +//! conditional blocks (no #5849 representation yet). +pub mod assertion_vocabulary; pub mod compose; pub mod gui_table; pub mod lower; @@ -209,9 +224,10 @@ pub fn parse(source: &str) -> Result { parse::Parser::new(source).parse_document() } -/// Stage 2 (vocabulary half): validate a parsed document against the -/// #5849 vocabulary — element registry, attribute registry, enum -/// domains, child/sibling rules, and binding-slot name rules. +/// Stage 2: validate a parsed document against the vocabularies — +/// the #5849 element registry, attribute registry, enum domains, +/// child/sibling rules, and binding-slot name rules, plus the +/// `assert` slot against the #5850 assertion vocabulary. /// /// # Errors /// diff --git a/pkgs/id/crates/id-render/src/lower.rs b/pkgs/id/crates/id-render/src/lower.rs index 3d8640b2a0..4eb1983308 100644 --- a/pkgs/id/crates/id-render/src/lower.rs +++ b/pkgs/id/crates/id-render/src/lower.rs @@ -18,9 +18,10 @@ //! [`ComposedDocument`] together, matching elements by document //! path; a path mismatch is a build error, never a guess. //! * **States are not lowered yet.** #5851 §3.6 state composition -//! operates on the #5850 state grammar, which reaches the -//! pipeline through the `assert` slot that stage 2 still carries -//! opaquely (see the crate documentation). Resolved properties +//! operates on state deltas, which #5850 §5 fixes as +//! target-derived from the base roles — the `assert` slot names +//! no per-state styling, so there is nothing state-shaped in +//! the resolved properties to lower. Resolved properties //! are the assertion dimensions of #5850's closed v1 set as //! adopted by #5851 A3. //! * **No silent fallback** (#5855 invariant 4, §3.3): an diff --git a/pkgs/id/crates/id-render/src/lower_gui.rs b/pkgs/id/crates/id-render/src/lower_gui.rs index 0924615fe9..46095fd9c1 100644 --- a/pkgs/id/crates/id-render/src/lower_gui.rs +++ b/pkgs/id/crates/id-render/src/lower_gui.rs @@ -41,6 +41,14 @@ //! never in the asset (§3 invariant 5): the artefact carries //! asset and renderer **names**, never content. //! +//! The report also accounts for every resolved assertion +//! (from the source `assert` slots and composition data alike) +//! by its disposition under the presentation decision — +//! governing the standard rendering, standing in on a fallback, +//! or superseded-but-retained as the fallback when an override +//! applies (#5854 §2.1 layer 4). No assertion is dropped +//! silently on this target either. +//! //! Native targets never reach this code: they ignore //! presentation overrides for standard controls (§4), which //! [`crate::lower_native`] records as exclusions. @@ -218,10 +226,34 @@ pub struct ExercisedFallback { pub warning: String, } +/// One resolved assertion of an element, accounted in the +/// report by what the presentation decision did to it (#5854 +/// §2.1 layer 4): an assertion governs the element's standard +/// rendering unless a presentation override supersedes it for +/// appearance — it then remains the fallback standard rendering, +/// never dead configuration. Raw-CSS winners are not assertions +/// and are accounted in `reported_overrides`, not here. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AssertionDisposition { + /// Element the assertion applies to. + pub element_path: String, + /// Assertion dimension. + pub property: String, + /// Role token that was resolved. + pub token: String, + /// `standard` (governs the standard rendering), + /// `fallback-standard` (an override fell back, so the + /// standard rendering it governs stood in, §2.4), or + /// `superseded-by-presentation` (an override governs the + /// appearance; the assertion remains the fallback). + pub disposition: String, +} + /// The stage-5 report for the GUI target: overrides applied, -/// fallbacks exercised, and the composition report's reported -/// overrides carried through. Deterministic in content and -/// order; no timestamps (#5855 invariant 2). +/// fallbacks exercised, the assertion accounting, and the +/// composition report's reported overrides carried through. +/// Deterministic in content and order; no timestamps (#5855 +/// invariant 2). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct GuiReport { /// Overrides applied, in document order. @@ -229,6 +261,9 @@ pub struct GuiReport { /// Fallbacks exercised, in document order — reported, never /// silent (§2.4). pub fallbacks: Vec, + /// Resolved assertions and their dispositions, in document + /// order — accounted, never silent (#5854 §2.1 layer 4). + pub assertions: Vec, /// Raw-CSS reported overrides, carried from the composition /// report (#5854 §6b). pub reported_overrides: Vec, @@ -344,6 +379,28 @@ fn lower_element( let presentation = decide_presentation(el, data, report, errors)?; + // Account for the element's resolved assertions under the + // presentation decision (#5854 §2.1 layer 4): they govern + // the standard rendering, stand in when an override falls + // back, and remain the fallback when one supersedes them. + let disposition = match &presentation { + GuiPresentation::Standard => "standard", + GuiPresentation::Fallback { .. } => "fallback-standard", + GuiPresentation::Asset { .. } | GuiPresentation::Drawn { .. } => { + "superseded-by-presentation" + } + }; + for prop in &el.properties { + if let Some(token) = &prop.token { + report.assertions.push(AssertionDisposition { + element_path: el.path.clone(), + property: prop.property.clone(), + token: token.clone(), + disposition: disposition.to_string(), + }); + } + } + let mut children = Vec::new(); for child in &el.children { children.push(match child { @@ -842,6 +899,24 @@ fn push_report_json(out: &mut String, report: &GuiReport, depth: usize) { } out.push(']'); out.push_str(",\n"); + field(out, "assertions"); + out.push('['); + for (i, a) in report.assertions.iter().enumerate() { + if i > 0 { + out.push_str(", "); + } + out.push_str("{\"element\": "); + push_json_string(out, &a.element_path); + out.push_str(", \"property\": "); + push_json_string(out, &a.property); + out.push_str(", \"token\": "); + push_json_string(out, &a.token); + out.push_str(", \"disposition\": "); + push_json_string(out, &a.disposition); + out.push('}'); + } + out.push(']'); + out.push_str(",\n"); field(out, "reported_overrides"); out.push('['); for (i, o) in report.reported_overrides.iter().enumerate() { diff --git a/pkgs/id/crates/id-render/src/lower_native.rs b/pkgs/id/crates/id-render/src/lower_native.rs index 9604fb934e..e3671cbc0d 100644 --- a/pkgs/id/crates/id-render/src/lower_native.rs +++ b/pkgs/id/crates/id-render/src/lower_native.rs @@ -31,9 +31,9 @@ //! raw-CSS winner is recorded as a platform-default entry, not //! carried as CSS text. //! * **States are not lowered.** As in the web lowering, #5851 -//! §3.6-style state composition operates on the #5850 state -//! grammar, which reaches the pipeline through the `assert` -//! slot stage 2 still carries opaquely. On native targets the +//! §3.6-style state composition operates on state deltas, which +//! #5850 §5 fixes as target-derived — the `assert` slot names +//! no per-state styling. On native targets the //! standard control's own state behaviour is the rendering //! (#5852 §3.8), checked against the contract by conformance, //! not re-created here. diff --git a/pkgs/id/crates/id-render/src/validate.rs b/pkgs/id/crates/id-render/src/validate.rs index 32141f752d..a00c9cba45 100644 --- a/pkgs/id/crates/id-render/src/validate.rs +++ b/pkgs/id/crates/id-render/src/validate.rs @@ -1,4 +1,4 @@ -//! Stage 2, vocabulary half — validate (#5855 §2.1). +//! Stage 2 — validate (#5855 §2.1). //! //! Checks a parsed document against the #5849 vocabulary, consumed as //! data from [`crate::vocabulary`]: required and allowed attributes, @@ -8,11 +8,16 @@ //! Every violation is a build error with a source location; all //! violations are collected before the build fails. //! -//! Not checked here, by design: the content of the `assert` slot. Its -//! grammar and role vocabulary are #5850's and unsettled; #5855 -//! assumption A2 has the pipeline carry assertions opaquely until the -//! vocabulary lands as versioned data. +//! The assertion half of the stage checks the `assert` slot against +//! the #5850 assertion vocabulary, consumed as versioned data from +//! [`crate::assertion_vocabulary`]: the slot's (dimension, +//! role-value) grammar, the closed dimension set and token domains, +//! the no-raw-values rule (#5850 invariant 1), and the +//! one-pair-per-dimension rule (#5854 §2.2). #5855 assumption A2 +//! carried the slot opaquely until #5850 settled; it has settled, +//! so the slot is checked here like every other vocabulary input. +use crate::assertion_vocabulary; use crate::vocabulary::{self, ElementSpec, FIELD_CONSTRAINT_KINDS}; use crate::{BuildError, Document, Element, Node}; @@ -56,6 +61,7 @@ fn validate_element( }; check_attributes(el, spec, parent, siblings, errors); + check_assert_slot(el, errors); check_enums(el, spec, errors); check_constraint_applicability(el, errors); check_child_rules(el, parent, errors); @@ -157,6 +163,44 @@ fn check_attributes( } } +/// The assertion half of stage 2: the `assert` slot checked +/// against the #5850 vocabulary (consumed as data from +/// [`crate::assertion_vocabulary`]). Unknown dimensions and tokens +/// fail with suggestions, in the #5849 idiom; raw values fail +/// under #5850 invariant 1; a dimension asserted twice in one +/// slot fails under #5854 §2.2. The slot does not apply to a +/// `` region: raw content is verbatim authored source, not +/// a rendered registry element (#5849 §3.1), so an assertion +/// there could never be honoured — it is an error, not a silent +/// drop. +fn check_assert_slot(el: &Element, errors: &mut Vec) { + if !el.has_attr("assert") { + return; + } + if el.name == "raw" { + errors.push(BuildError::new( + "the `assert` slot does not apply to a region: raw content is \ + verbatim authored source, not a rendered element (#5849 §3.1)", + el.span.line, + el.span.col, + )); + return; + } + let Some(value) = el.attr("assert") else { + errors.push(BuildError::new( + format!("attribute `assert` on <{}> requires a value", el.name), + el.span.line, + el.span.col, + )); + return; + }; + if let Err(problems) = assertion_vocabulary::parse_assert_slot(value) { + for problem in problems { + errors.push(BuildError::new(problem, el.span.line, el.span.col)); + } + } +} + fn is_sole_section(siblings: &[Node]) -> bool { siblings .iter() diff --git a/pkgs/id/crates/id-render/tests/assertions.rs b/pkgs/id/crates/id-render/tests/assertions.rs new file mode 100644 index 0000000000..97e887426d --- /dev/null +++ b/pkgs/id/crates/id-render/tests/assertions.rs @@ -0,0 +1,375 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +//! Behaviour tests for the assertion half of stage 2 and its +//! passage through stages 3–5: the `assert` slot consumed +//! against the #5850 assertion vocabulary (the discharge of +//! #5855 assumption A2). Each test names the decision-record +//! behaviour it verifies. + +use std::collections::BTreeSet; + +use id_render::assertion_vocabulary::{self, DIMENSIONS}; +use id_render::compose::{AssertionInput, ComposeData, OverrideInput, Specificity, TargetSpec}; +use id_render::lower_gui::{GuiData, GuiOverrideDef, PresentationKind}; +use id_render::{ + compose_document, lower_document, lower_document_gui, lower_document_native, + parse_and_validate, +}; + +const BUTTON_PATH: &str = "document/page[0]/form[0]/button[0]"; +const CARD_PATH: &str = "document/page[0]/card[0]"; + +/// One assertion-bearing source rendered by the three-target +/// tests: the #5850 §2 examples made concrete (a primary +/// call-to-action carries emphasis primary and tone accent; a +/// card carries elevation raised and pad space-3). +const ASSERTING_DOC: &str = r#" + + Settings + + Your public profile. + +
+ +
+
+
"#; + +fn target(name: &str) -> TargetSpec { + TargetSpec { + name: name.to_string(), + form_factor: "desktop".to_string(), + capabilities: BTreeSet::new(), + } +} + +fn doc_with_assert(assert: &str) -> String { + format!( + r#"
"# + ) +} + +#[test] +fn assert_slot_parses_dimension_token_pairs_decision_5850_s2() { + // #5850 §2: an assertion is a (dimension, role-value) pair; + // the slot is a comma-separated list of pairs. + let pairs = assertion_vocabulary::parse_assert_slot("tone accent, emphasis primary") + .expect("the §2 example pairs parse"); + assert_eq!(pairs.len(), 2); + assert_eq!(pairs[0].dimension, "tone"); + assert_eq!(pairs[0].token, "accent"); + assert_eq!(pairs[1].dimension, "emphasis"); + assert_eq!(pairs[1].token, "primary"); + + // And the full pipeline accepts the slot in source. + let doc = parse_and_validate(&doc_with_assert("tone accent, emphasis primary")) + .expect("a vocabulary-conforming slot validates"); + assert_eq!(doc.version(), Some("1")); +} + +#[test] +fn every_vocabulary_token_validates_decision_5850_s2() { + // The validator and the vocabulary table must agree exactly: + // every (dimension, token) pair the #5850 data names is + // accepted in the slot, on an ordinary element. + for dimension in DIMENSIONS { + for token in dimension.tokens { + let src = doc_with_assert(&format!("{} {token}", dimension.name)); + assert!( + parse_and_validate(&src).is_ok(), + "{} {token} must validate", + dimension.name + ); + } + } +} + +#[test] +fn assert_slot_unknown_dimension_fails_with_suggestions_decision_5850_s2() { + // The #5849 idiom, applied to the assertion vocabulary: an + // unknown dimension is a build error naming the closed set + // and the nearest dimensions. + let errors = parse_and_validate(&doc_with_assert("tonee accent")) + .expect_err("a typo'd dimension must fail validation"); + assert!( + errors + .iter() + .any(|e| e.message.contains("unknown assertion dimension `tonee`") + && e.message.contains("tone")), + "{errors:?}" + ); +} + +#[test] +fn assert_slot_unknown_token_fails_with_suggestions_decision_5850_s2() { + let errors = parse_and_validate(&doc_with_assert("tone acceent")) + .expect_err("a typo'd role token must fail validation"); + assert!( + errors + .iter() + .any(|e| e.message.contains("unknown assertion token `acceent`") + && e.message.contains("accent")), + "{errors:?}" + ); + // A token from another dimension's domain is equally unknown + // here: domains are per-dimension. + let errors = parse_and_validate(&doc_with_assert("tone heading")) + .expect_err("a text role is not a tone role"); + assert!( + errors + .iter() + .any(|e| e.message.contains("unknown assertion token `heading`")), + "{errors:?}" + ); +} + +#[test] +fn assert_slot_rejects_raw_values_decision_5850_invariant_1() { + // Invariant 1: no hex colours, no sizes, no font names in + // assertions — content names roles only. + for bad in ["tone #bada55", "pad 12px", "text Arial"] { + let errors = parse_and_validate(&doc_with_assert(bad)) + .expect_err("a raw value must fail validation"); + assert!( + errors + .iter() + .any(|e| e.message.contains("not a role name")), + "{bad}: {errors:?}" + ); + } +} + +#[test] +fn assert_slot_rejects_malformed_pairs_decision_5850_s2() { + for bad in ["accent", "tone", "tone accent extra", ""] { + let errors = parse_and_validate(&doc_with_assert(bad)) + .expect_err("a malformed slot must fail validation"); + assert!( + errors.iter().any(|e| e.message.contains("`assert`")), + "{bad:?}: {errors:?}" + ); + } + // A bare `assert` attribute carries no expression at all. + let src = r#"
"#; + let errors = parse_and_validate(src).expect_err("a bare assert must fail"); + assert!( + errors + .iter() + .any(|e| e.message.contains("`assert` on "# @@ -199,23 +216,7 @@ fn source_assertions_compose_at_instance_specificity_decision_5854_s2_2() { ..Default::default() }; let composed = compose_document(&doc, &target("web"), &data).expect("composes"); - fn find<'a>( - node: &'a id_render::compose::ComposedElement, - path: &str, - ) -> Option<&'a id_render::compose::ComposedElement> { - if node.path == path { - return Some(node); - } - for child in &node.children { - if let id_render::compose::ComposedNode::Element(el) = child - && let Some(found) = find(el, path) - { - return Some(found); - } - } - None - } - let button = find(&composed.root, BUTTON_PATH).expect("button present"); + let button = find_composed(&composed.root, BUTTON_PATH).expect("button present"); assert_eq!(button.properties.len(), 1); assert_eq!(button.properties[0].token.as_deref(), Some("accent"));