diff --git a/.claude/skills/medui-authoring/SKILL.md b/.claude/skills/medui-authoring/SKILL.md index df3c6b7..30f6350 100644 --- a/.claude/skills/medui-authoring/SKILL.md +++ b/.claude/skills/medui-authoring/SKILL.md @@ -6,7 +6,10 @@ description: Author or modify .medui UI screens — the build-time-only MedUI DS # MedUI authoring `.medui` files are compiled at build time into a static `CompiledScreenPackage` — nothing is -parsed, laid out, or shaped on-device (ADR-008/009). The full reference lives in `docs/dsl/`: +parsed, laid out, or shaped on-device (ADR-008/009). The implementation pins the canonical +language contract in `medui-conformance.toml`; portable grammar, diagnostic, and authoring rules +live in [`Compliatory/MedUI`](https://github.com/Compliatory/MedUI). TrustSC-specific integration +reference lives in `docs/dsl/`: `overview.md`, `language-reference.md`, `component-dictionary.md`, `safety-monitor-contract.md`, `build-integration.md`. Worked examples: `examples/hello_world/hello_world.medui` (minimal) and `examples/class_c_monitor/` (full NeuroSense 500 screen). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a592cd8..5d1d9c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,25 @@ jobs: - name: Check out repository uses: actions/checkout@v4 + - name: Resolve the pinned MedUI contract commit + id: medui-contract + run: | + set -euo pipefail + commit="$(sed -n 's/^[[:space:]]*commit[[:space:]]*=[[:space:]]*"\([0-9A-Fa-f]\{40\}\)"[[:space:]]*$/\1/p' medui-conformance.toml)" + if [ -z "$commit" ]; then + echo "medui-conformance.toml has no 40-character commit pin" >&2 + exit 1 + fi + echo "commit=$commit" >> "$GITHUB_OUTPUT" + + - name: Check out pinned MedUI conformance contract + uses: actions/checkout@v4 + with: + repository: Compliatory/MedUI + ref: ${{ steps.medui-contract.outputs.commit }} + path: .medui-conformance + persist-credentials: false + - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable @@ -34,6 +53,8 @@ jobs: run: cargo build --locked --workspace - name: Run test suite + env: + MEDUI_CONFORMANCE_DIR: ${{ github.workspace }}/.medui-conformance run: cargo test --locked --quiet - name: Lint regulatory citations and Justification blocks (ADR-020) diff --git a/.gitignore b/.gitignore index b365125..480ba51 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /target +.DS_Store CLAUDE.md .claude/settings.local.json diff --git a/Cargo.lock b/Cargo.lock index 47218a6..d5fcd27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1865,6 +1865,7 @@ dependencies = [ name = "trustsc-medui-check" version = "0.1.0" dependencies = [ + "serde_json", "trustsc", "trustsc-ui-dsl-authoring", ] diff --git a/crates/trustsc-core/src/lib.rs b/crates/trustsc-core/src/lib.rs index 90c7dff..f12a703 100644 --- a/crates/trustsc-core/src/lib.rs +++ b/crates/trustsc-core/src/lib.rs @@ -7,14 +7,56 @@ pub type TrustScResult = Result; #[derive(Clone, Debug, Eq, PartialEq)] pub struct ValidationError { message: String, + code: Option<&'static str>, + line: Option, + column: Option, } impl ValidationError { pub fn new(message: impl Into) -> Self { Self { message: message.into(), + code: None, + line: None, + column: None, } } + + /// An error tagged with a stable machine-readable identity assigned by the producing crate. + /// + /// The identity is deliberately opaque here: this crate does not own any code registry, it + /// only carries the tag so a caller can route on it without re-deriving meaning from + /// [`Display`] output, which is free to be reworded. + pub fn with_code(code: &'static str, message: impl Into) -> Self { + Self { + message: message.into(), + code: Some(code), + line: None, + column: None, + } + } + + /// Attaches a structured source position supplied by the producing crate. + pub fn with_position(mut self, line: Option, column: Option) -> Self { + self.line = line; + self.column = column; + self + } + + /// The stable identity assigned at the point the error was raised, when there is one. + pub fn code(&self) -> Option<&'static str> { + self.code + } + + /// The 1-based source line assigned at the raise site, when known. + pub fn line(&self) -> Option { + self.line + } + + /// The 1-based source column assigned at the raise site, when known. + pub fn column(&self) -> Option { + self.column + } } impl Display for ValidationError { @@ -153,4 +195,15 @@ mod tests { assert_eq!(error.to_string(), "manufacturer must not be empty"); } + + #[test] + fn validation_error_carries_structured_metadata() { + let error = ValidationError::with_code("TEST-E001", "message mentioning line 99") + .with_position(Some(7), Some(3)); + + assert_eq!(error.code(), Some("TEST-E001")); + assert_eq!(error.line(), Some(7)); + assert_eq!(error.column(), Some(3)); + assert_eq!(error.to_string(), "message mentioning line 99"); + } } diff --git a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs index 81a373b..53f63fc 100644 --- a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs +++ b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs @@ -6,44 +6,115 @@ use trustsc_core::ValidationError; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Severity { Error, + Warning, + Note, } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Diagnostic { + /// Stable implementation-neutral identity from `Compliatory/MedUI`. + pub code: &'static str, + /// Source path supplied by the caller; empty for in-memory input. + pub file: String, pub message: String, pub line: Option, + /// 1-based UTF-8 byte column, or `None` when the legacy parser cannot locate it precisely. + pub column: Option, pub severity: Severity, + pub fix_hint: String, } impl Diagnostic { - /// Extracts the line number from a [`ValidationError`]'s message, if present. Every parser - /// error in this crate embeds the source line as `line {N}` somewhere in the message (not - /// always at the end — e.g. `"component at line {n} must declare \`id\`"`), so this scans for - /// the last `line ` occurrence followed by a run of ASCII digits rather than assuming a fixed - /// position. + /// Builds the shared diagnostic envelope from an error raised inside this crate. + /// + /// The code is read from the error itself — assigned at the point the condition was + /// detected — never re-derived from the message. `spec/diagnostics.md` states that a message + /// "may be reworded" while a code's meaning is stable, so inferring one from the other would + /// make a stable identity depend on prose. + /// + /// Source positions are carried independently of the human-readable message. The current + /// line-oriented parser supplies a line but no column; compilation failures without a + /// source anchor leave both absent. pub fn from_validation_error(error: &ValidationError) -> Diagnostic { let message = error.to_string(); - let line = extract_line_number(&message); Diagnostic { + // An untagged error means a raise site in this crate forgot its code, or an error + // crossed in from another crate. `assigns_a_code_to_every_raise_site` covers the + // first; the fallback keeps the envelope well-formed for the second. + code: error.code().unwrap_or(code::UNEXPECTED_TOKEN), + file: String::new(), message, - line, + line: error.line(), + column: error.column(), severity: Severity::Error, + fix_hint: String::new(), } } } -fn extract_line_number(message: &str) -> Option { - let mut search = message; - let mut found = None; - while let Some(index) = search.find("line ") { - let after = &search[index + "line ".len()..]; - let digits: String = after.chars().take_while(|c| c.is_ascii_digit()).collect(); - if !digits.is_empty() { - found = digits.parse().ok(); - } - search = &search[index + "line ".len()..]; - } - found +/// The `MEDUI-E###` identities from the pinned contract's `spec/diagnostics.md`, named by meaning +/// so a raise site reads as the condition it detects. +/// +/// A code's meaning never changes and a retired number is never reused (`MEDUI-DEC-005`), so +/// these constants are append-only. Codes the contract registers but this implementation never +/// raises — `MEDUI-E004` (source is not UTF-8), `MEDUI-E017` (hardcoded product string), +/// `MEDUI-E053` (dynamic text escapes its charset) — are deliberately absent rather than +/// declared and unused. +pub mod code { + /// `MEDUI-E003` — the `.medui` source could not be read. + pub const SOURCE_UNREADABLE: &str = "MEDUI-E003"; + /// `MEDUI-E010` — the source does not parse. + pub const UNEXPECTED_TOKEN: &str = "MEDUI-E010"; + /// `MEDUI-E011` — the component name is not in the closed dictionary. + pub const UNKNOWN_COMPONENT: &str = "MEDUI-E011"; + /// `MEDUI-E012` — a construct omits a field its schema requires. + pub const MISSING_FIELD: &str = "MEDUI-E012"; + /// `MEDUI-E013` — a construct declares a field its schema does not define. + pub const UNKNOWN_FIELD: &str = "MEDUI-E013"; + /// `MEDUI-E014` — two nodes resolve to the same id. + pub const DUPLICATE_NODE_ID: &str = "MEDUI-E014"; + /// `MEDUI-E015` — a `Row` nests inside another `Row`. + pub const NESTED_ROW: &str = "MEDUI-E015"; + /// `MEDUI-E016` — a construct the language forbids in this position. + pub const FORBIDDEN_CONSTRUCT: &str = "MEDUI-E016"; + /// `MEDUI-E030` — the theme colour token is not approved. + pub const UNKNOWN_COLOR_TOKEN: &str = "MEDUI-E030"; + /// `MEDUI-E031` — the text key does not exist in the approved package. + pub const UNKNOWN_TEXT_KEY: &str = "MEDUI-E031"; + /// `MEDUI-E032` — the text key exists but an approved locale has no run for it. + pub const TEXT_KEY_MISSING_LOCALE: &str = "MEDUI-E032"; + /// `MEDUI-E050` — rendered text does not fit its box in the worst approved case. + pub const TEXT_BUDGET_EXCEEDED: &str = "MEDUI-E050"; + /// `MEDUI-E051` — a node escapes its container or collides with another. + pub const LAYOUT_OVERFLOW: &str = "MEDUI-E051"; + /// `MEDUI-E052` — resolved geometry leaves the screen surface. + pub const SURFACE_EXCEEDED: &str = "MEDUI-E052"; + /// `MEDUI-E071` — a CV check is not one the contract defines for this node. + pub const UNKNOWN_CV_CHECK: &str = "MEDUI-E071"; + + /// A condition the pinned registry has no code for, reported as `MEDUI-E010` until one + /// exists. + /// + /// `spec/component-model.md` makes unknown image IDs, templates, charsets, clock formats, + /// system events, and layout kinds fatal, but registers a code only for colour tokens + /// (`MEDUI-E030`) and CV checks (`MEDUI-E071`). Marking these sites explicitly keeps them + /// greppable as registry gaps to raise upstream, instead of letting them fall through a + /// catch-all unnoticed. + pub const UNREGISTERED: &str = UNEXPECTED_TOKEN; +} + +/// Raises an error carrying the stable identity of the condition that produced it. +pub(crate) fn coded(code: &'static str, message: impl Into) -> ValidationError { + ValidationError::with_code(code, message) +} + +/// Raises a parser error with its structured 1-based line position. +pub(crate) fn coded_at( + line_number: usize, + code: &'static str, + message: impl Into, +) -> ValidationError { + coded(code, message).with_position(u32::try_from(line_number).ok(), None) } #[cfg(test)] @@ -51,23 +122,16 @@ mod tests { use super::*; #[test] - fn extracts_line_number_mid_sentence() { - assert_eq!( - extract_line_number("component at line 12 must declare `id`"), - Some(12) - ); - } + fn diagnostic_uses_structured_position_instead_of_message_text() { + let positioned = ValidationError::with_code(code::UNEXPECTED_TOKEN, "no line in prose") + .with_position(Some(12), None); + let unpositioned = + ValidationError::with_code(code::UNKNOWN_COLOR_TOKEN, "untrusted token says line 99"); - #[test] - fn extracts_line_number_at_end() { assert_eq!( - extract_line_number("unexpected content after screen closing brace at line 40"), - Some(40) + Diagnostic::from_validation_error(&positioned).line, + Some(12) ); - } - - #[test] - fn returns_none_without_line_number() { - assert_eq!(extract_line_number("id must not be empty"), None); + assert_eq!(Diagnostic::from_validation_error(&unpositioned).line, None); } } diff --git a/crates/trustsc-ui-dsl-authoring/src/lib.rs b/crates/trustsc-ui-dsl-authoring/src/lib.rs index 44b1628..47fca0c 100644 --- a/crates/trustsc-ui-dsl-authoring/src/lib.rs +++ b/crates/trustsc-ui-dsl-authoring/src/lib.rs @@ -6,7 +6,7 @@ use std::{ path::Path, }; -use trustsc_core::{TrustScResult, ValidationError}; +use trustsc_core::TrustScResult; use trustsc_image_schema::ImagePackage; use trustsc_text_schema::{CompiledTextRun, NumericGlyphSet, TextPackage}; use trustsc_ui::{ClockFormat, CvCheckKind, LayoutKind, SystemEvent, THEME_COLORS, resolve_color_token}; @@ -58,11 +58,11 @@ fn resolve_display_template<'a>( .filter(|package| package.find_template(template_id).is_some()); match (matches.next(), matches.next()) { (Some(package), None) => Ok(package), - (None, _) => Err(ValidationError::new(format!( + (None, _) => Err(coded(code::UNREGISTERED, format!( "NumericDisplay {node_id} references unknown template {template_id} (searched {} display packages)", displays.len() ))), - (Some(_), Some(_)) => Err(ValidationError::new(format!( + (Some(_), Some(_)) => Err(coded(code::UNREGISTERED, format!( "NumericDisplay {node_id} template {template_id} is ambiguous across display packages" ))), } @@ -130,7 +130,9 @@ pub use catalog::{ widget_catalog, }; pub use serialize::serialize_screen; -pub use diagnostic::{Diagnostic, Severity}; +pub use diagnostic::{Diagnostic, Severity, code}; + +use diagnostic::{coded, coded_at}; pub fn compile_medui_file_to_rust_module( input_path: impl AsRef, @@ -142,7 +144,7 @@ pub fn compile_medui_file_to_rust_module( let input_path = input_path.as_ref(); let output_path = output_path.as_ref(); let source = fs::read_to_string(input_path).map_err(|error| { - ValidationError::new(format!( + coded(code::SOURCE_UNREADABLE, format!( "failed to read MedUI source {}: {error}", input_path.display() )) @@ -152,14 +154,14 @@ pub fn compile_medui_file_to_rust_module( if let Some(parent) = output_path.parent() { fs::create_dir_all(parent).map_err(|error| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "failed to create MedUI output directory {}: {error}", parent.display() )) })?; } fs::write(output_path, generated).map_err(|error| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "failed to write generated MedUI module {}: {error}", output_path.display() )) @@ -176,16 +178,25 @@ pub fn compile_medui_source_to_rust( ) -> TrustScResult { let compiled = compile_medui_source(source, &options, text_packages, image_packages) .map_err(|diagnostics| { - let joined = diagnostics - .iter() - .map(|diagnostic| diagnostic.message.as_str()) - .collect::>() - .join("; "); - ValidationError::new(if joined.is_empty() { - "compilation failed with no diagnostics".to_string() - } else { - joined - }) + // A single diagnostic keeps its own identity: this string-returning entry point is + // what `build.rs` and the CLI use, and collapsing every failure to one catch-all code + // would lose exactly what the raise sites were tagged to preserve. Only a genuine + // multi-diagnostic join has no single identity to carry. + match diagnostics.as_slice() { + [] => coded( + code::UNEXPECTED_TOKEN, + "compilation failed with no diagnostics", + ), + [only] => coded(only.code, only.message.clone()) + .with_position(only.line, only.column), + many => coded( + code::UNEXPECTED_TOKEN, + many.iter() + .map(|diagnostic| diagnostic.message.as_str()) + .collect::>() + .join("; "), + ), + } })?; Ok(emit_rust_module(&compiled, options.crate_path)) } @@ -237,7 +248,9 @@ fn parse_screen(source: &str) -> TrustScResult { .collect::>(); if lines.len() < 3 { - return Err(ValidationError::new( + return Err(coded_at( + lines.first().map_or(1, |(line, _)| *line), + code::UNEXPECTED_TOKEN, "MedUI source must contain a screen header, layout, and closing brace", )); } @@ -267,7 +280,7 @@ fn parse_screen(source: &str) -> TrustScResult { let (line_number, line) = &lines[cursor]; if line == "}" { if cursor != lines.len() - 1 { - return Err(ValidationError::new(format!( + return Err(coded_at(*line_number, code::UNEXPECTED_TOKEN, format!( "unexpected content after screen closing brace at line {line_number}" ))); } @@ -282,7 +295,7 @@ fn parse_screen(source: &str) -> TrustScResult { if line == "Row {" { if pending_safety.is_some() { - return Err(ValidationError::new(format!( + return Err(coded_at(*line_number, code::FORBIDDEN_CONSTRUCT, format!( "@safety_critical cannot annotate a Row container at line {line_number}" ))); } @@ -316,7 +329,9 @@ fn parse_screen(source: &str) -> TrustScResult { } if items.is_empty() { - return Err(ValidationError::new( + return Err(coded_at( + *screen_line, + code::MISSING_FIELD, "MedUI screen must declare at least one component", )); } @@ -359,7 +374,7 @@ fn parse_row( } if line == "Row {" { - return Err(ValidationError::new(format!( + return Err(coded_at(*line_number, code::NESTED_ROW, format!( "nested Row containers are not supported at line {line_number}" ))); } @@ -399,7 +414,7 @@ fn parse_row( // Scalar Row property. let property_line = line.trim_end_matches(';'); let (key, value) = property_line.split_once(':').ok_or_else(|| { - ValidationError::new(format!( + coded_at(*line_number, code::UNEXPECTED_TOKEN, format!( "invalid Row property `{property_line}` at line {line_number}" )) })?; @@ -413,7 +428,7 @@ fn parse_row( background = Some(parse_non_empty(*line_number, "background", value.trim())?) } other => { - return Err(ValidationError::new(format!( + return Err(coded_at(*line_number, code::UNKNOWN_FIELD, format!( "unsupported Row property `{other}` at line {line_number}" ))); } @@ -422,19 +437,19 @@ fn parse_row( } if !closed { - return Err(ValidationError::new(format!( + return Err(coded_at(row_line_number, code::UNEXPECTED_TOKEN, format!( "Row starting at line {row_line_number} is missing its closing brace" ))); } let id = id.ok_or_else(|| { - ValidationError::new(format!("Row at line {row_line_number} must declare `id`")) + coded_at(row_line_number, code::MISSING_FIELD, format!("Row at line {row_line_number} must declare `id`")) })?; let height = height.ok_or_else(|| { - ValidationError::new(format!("Row {id} must declare `height`")) + coded_at(row_line_number, code::MISSING_FIELD, format!("Row {id} must declare `height`")) })?; if children.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded_at(row_line_number, code::MISSING_FIELD, format!( "Row {id} must contain at least one component" ))); } @@ -457,7 +472,7 @@ fn parse_screen_header(line_number: usize, line: &str) -> TrustScResult .and_then(|rest| rest.strip_suffix('{')) .map(str::trim) .ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "expected `Screen {{` at line {line_number}" )) })?; @@ -468,9 +483,15 @@ fn parse_layout(line_number: usize, line: &str) -> TrustScResult TrustScResult LayoutKind::Vertical, "Horizontal" => LayoutKind::Horizontal, other => { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported layout `{other}` at line {line_number}" ))) } @@ -500,13 +521,17 @@ fn parse_inline_px_property(line_number: usize, block: &str, key: &str) -> Trust .map(str::trim) .find(|entry| entry.starts_with(&format!("{key}:"))) .ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::MISSING_FIELD, format!( "layout block at line {line_number} must declare `{key}`" )) }) .and_then(|entry| { let (_, value) = entry.split_once(':').ok_or_else(|| { - ValidationError::new(format!("invalid layout property `{entry}` at line {line_number}")) + coded_at( + line_number, + code::UNEXPECTED_TOKEN, + format!("invalid layout property `{entry}` at line {line_number}"), + ) })?; parse_px_allowing_zero(line_number, key, value.trim()) }) @@ -518,7 +543,7 @@ fn parse_safety_critical(line_number: usize, line: &str) -> TrustScResult TrustScResult Ok(CvCheckKind::Bounds), "ColorHash" => Ok(CvCheckKind::ColorHash), - other => Err(ValidationError::new(format!( + other => Err(coded_at(line_number, code::UNKNOWN_CV_CHECK, format!( "unsupported CV check `{other}` at line {line_number}" ))), }) .collect::>>()?; if cv_checks.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::MISSING_FIELD, format!( "safety-critical annotation at line {line_number} must declare at least one CV check" ))); } @@ -561,7 +586,13 @@ fn parse_component_start(line_number: usize, line: &str) -> TrustScResult Ok(ComponentKind::CriticalButton), "VulkanViewport" => Ok(ComponentKind::VulkanViewport), @@ -573,7 +604,7 @@ fn parse_component_start(line_number: usize, line: &str) -> TrustScResult Ok(ComponentKind::Image), "Button" => Ok(ComponentKind::Button), "TextInput" => Ok(ComponentKind::TextInput), - other => Err(ValidationError::new(format!( + other => Err(coded_at(line_number, code::UNKNOWN_COMPONENT, format!( "unsupported component `{other}` at line {line_number}" ))), } @@ -606,7 +637,7 @@ fn parse_component_properties( for (property_line_number, property_line) in properties { let property_line = property_line.trim_end_matches(';'); let (key, value) = property_line.split_once(':').ok_or_else(|| { - ValidationError::new(format!( + coded_at(*property_line_number, code::UNEXPECTED_TOKEN, format!( "invalid property `{property_line}` at line {property_line_number}" )) })?; @@ -647,7 +678,7 @@ fn parse_component_properties( } "charset" => charset = Some(parse_charset(*property_line_number, value)?), other => { - return Err(ValidationError::new(format!( + return Err(coded_at(*property_line_number, code::UNKNOWN_FIELD, format!( "unsupported property `{other}` at line {property_line_number}" ))) } @@ -655,17 +686,17 @@ fn parse_component_properties( } let id = id.ok_or_else(|| { - ValidationError::new(format!("component at line {line_number} must declare `id`")) + coded_at(line_number, code::MISSING_FIELD, format!("component at line {line_number} must declare `id`")) })?; let width = width.ok_or_else(|| { - ValidationError::new(format!("component {id} must declare `width`")) + coded_at(line_number, code::MISSING_FIELD, format!("component {id} must declare `width`")) })?; let height = height.ok_or_else(|| { - ValidationError::new(format!("component {id} must declare `height`")) + coded_at(line_number, code::MISSING_FIELD, format!("component {id} must declare `height`")) })?; if position.is_some() && (width == Dimension::Fill || height == Dimension::Fill) { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::LAYOUT_OVERFLOW, format!( "component {id}: `position` requires fixed `width`/`height` — Fill is flow-only" ))); } @@ -673,77 +704,77 @@ fn parse_component_properties( let kind = match component_kind { ComponentKind::CriticalButton => NodeKind::CriticalButton { requirement_id: requirement_id.ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::MISSING_FIELD, format!( "CriticalButton {id} must declare `requirement`" )) })?, label_text_key: label_text_key.ok_or_else(|| { - ValidationError::new(format!("CriticalButton {id} must declare `label`")) + coded_at(line_number, code::MISSING_FIELD, format!("CriticalButton {id} must declare `label`")) })?, color_token: color_token.ok_or_else(|| { - ValidationError::new(format!("CriticalButton {id} must declare `color`")) + coded_at(line_number, code::MISSING_FIELD, format!("CriticalButton {id} must declare `color`")) })?, on_press: on_press.ok_or_else(|| { - ValidationError::new(format!("CriticalButton {id} must declare `on_press`")) + coded_at(line_number, code::MISSING_FIELD, format!("CriticalButton {id} must declare `on_press`")) })?, }, ComponentKind::VulkanViewport => NodeKind::VulkanViewport { stream_source: stream_source.ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::MISSING_FIELD, format!( "VulkanViewport {id} must declare `stream_source`" )) })?, }, ComponentKind::SignalTrace => NodeKind::SignalTrace { stream_source: stream_source.ok_or_else(|| { - ValidationError::new(format!("SignalTrace {id} must declare `stream_source`")) + coded_at(line_number, code::MISSING_FIELD, format!("SignalTrace {id} must declare `stream_source`")) })?, color_token: color_token.ok_or_else(|| { - ValidationError::new(format!("SignalTrace {id} must declare `color`")) + coded_at(line_number, code::MISSING_FIELD, format!("SignalTrace {id} must declare `color`")) })?, }, ComponentKind::Label => NodeKind::Label { text_key: text_key.ok_or_else(|| { - ValidationError::new(format!("Label {id} must declare `text`")) + coded_at(line_number, code::MISSING_FIELD, format!("Label {id} must declare `text`")) })?, color_token: color_token.ok_or_else(|| { - ValidationError::new(format!("Label {id} must declare `color`")) + coded_at(line_number, code::MISSING_FIELD, format!("Label {id} must declare `color`")) })?, }, ComponentKind::Clock => NodeKind::Clock { format: clock_format.ok_or_else(|| { - ValidationError::new(format!("Clock {id} must declare `format`")) + coded_at(line_number, code::MISSING_FIELD, format!("Clock {id} must declare `format`")) })?, }, ComponentKind::NumericDisplay => NodeKind::NumericDisplay { requirement_id: requirement_id.ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::MISSING_FIELD, format!( "NumericDisplay {id} must declare `requirement`" )) })?, template_id: template_id.ok_or_else(|| { - ValidationError::new(format!("NumericDisplay {id} must declare `template`")) + coded_at(line_number, code::MISSING_FIELD, format!("NumericDisplay {id} must declare `template`")) })?, source: { let (source_line, raw) = source.ok_or_else(|| { - ValidationError::new(format!("NumericDisplay {id} must declare `source`")) + coded_at(line_number, code::MISSING_FIELD, format!("NumericDisplay {id} must declare `source`")) })?; parse_quoted(source_line, "source", &raw)? }, color_token: color_token.ok_or_else(|| { - ValidationError::new(format!("NumericDisplay {id} must declare `color`")) + coded_at(line_number, code::MISSING_FIELD, format!("NumericDisplay {id} must declare `color`")) })?, }, ComponentKind::StatusIndicator => { let state_text_keys = state_text_keys.ok_or_else(|| { - ValidationError::new(format!("StatusIndicator {id} must declare `states`")) + coded_at(line_number, code::MISSING_FIELD, format!("StatusIndicator {id} must declare `states`")) })?; // `colors` is optional: absent means every state uses the neutral status token. let color_tokens = color_tokens.unwrap_or_else(|| { vec!["Theme.Colors.Neutral".to_string(); state_text_keys.len()] }); if color_tokens.len() != state_text_keys.len() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNREGISTERED, format!( "StatusIndicator {id} declares {} states but {} colors", state_text_keys.len(), color_tokens.len() @@ -751,13 +782,13 @@ fn parse_component_properties( } NodeKind::StatusIndicator { requirement_id: requirement_id.ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::MISSING_FIELD, format!( "StatusIndicator {id} must declare `requirement`" )) })?, source: { let (source_line, raw) = source.ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::MISSING_FIELD, format!( "StatusIndicator {id} must declare `source`" )) })?; @@ -770,27 +801,27 @@ fn parse_component_properties( ComponentKind::Image => NodeKind::Image { image_id: { let (source_line, raw) = source.ok_or_else(|| { - ValidationError::new(format!("Image {id} must declare `source`")) + coded_at(line_number, code::MISSING_FIELD, format!("Image {id} must declare `source`")) })?; parse_image_key(source_line, &raw)? }, }, ComponentKind::Button => { if on_press.is_some() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::FORBIDDEN_CONSTRUCT, format!( "Button {id} must not declare `on_press` — framework-governed system events belong to CriticalButton (ADR-015)" ))); } NodeKind::Button { label_text_key: label_text_key.ok_or_else(|| { - ValidationError::new(format!("Button {id} must declare `label`")) + coded_at(line_number, code::MISSING_FIELD, format!("Button {id} must declare `label`")) })?, color_token: color_token.ok_or_else(|| { - ValidationError::new(format!("Button {id} must declare `color`")) + coded_at(line_number, code::MISSING_FIELD, format!("Button {id} must declare `color`")) })?, source: { let (source_line, raw) = source.ok_or_else(|| { - ValidationError::new(format!("Button {id} must declare `source`")) + coded_at(line_number, code::MISSING_FIELD, format!("Button {id} must declare `source`")) })?; parse_quoted(source_line, "source", &raw)? }, @@ -799,25 +830,25 @@ fn parse_component_properties( } ComponentKind::TextInput => { if on_press.is_some() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::FORBIDDEN_CONSTRUCT, format!( "TextInput {id} must not declare `on_press` — framework-governed system events belong to CriticalButton (ADR-015)" ))); } NodeKind::TextInput { source: { let (source_line, raw) = source.ok_or_else(|| { - ValidationError::new(format!("TextInput {id} must declare `source`")) + coded_at(line_number, code::MISSING_FIELD, format!("TextInput {id} must declare `source`")) })?; parse_quoted(source_line, "source", &raw)? }, max_length: max_length.ok_or_else(|| { - ValidationError::new(format!("TextInput {id} must declare `max_length`")) + coded_at(line_number, code::MISSING_FIELD, format!("TextInput {id} must declare `max_length`")) })?, // `charset` is optional: absent means the printable-ASCII default (ADR-015). glyph_set_id: charset .unwrap_or_else(|| ASCII_TEXT_GLYPH_SET_ID.to_string()), color_token: color_token.ok_or_else(|| { - ValidationError::new(format!("TextInput {id} must declare `color`")) + coded_at(line_number, code::MISSING_FIELD, format!("TextInput {id} must declare `color`")) })?, requirement_id, } @@ -837,7 +868,7 @@ fn parse_component_properties( fn parse_identifier(line_number: usize, field_name: &str, raw: &str) -> TrustScResult { let value = raw.trim(); if value.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -845,7 +876,7 @@ fn parse_identifier(line_number: usize, field_name: &str, raw: &str) -> TrustScR .chars() .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-')) { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} contains unsupported characters at line {line_number}" ))); } @@ -855,7 +886,7 @@ fn parse_identifier(line_number: usize, field_name: &str, raw: &str) -> TrustScR fn parse_non_empty(line_number: usize, field_name: &str, raw: &str) -> TrustScResult { let value = raw.trim(); if value.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -864,14 +895,14 @@ fn parse_non_empty(line_number: usize, field_name: &str, raw: &str) -> TrustScRe fn parse_quoted(line_number: usize, field_name: &str, raw: &str) -> TrustScResult { let value = raw.trim(); - if !(value.starts_with('"') && value.ends_with('"')) { - return Err(ValidationError::new(format!( + if value.len() < 2 || !(value.starts_with('"') && value.ends_with('"')) { + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must be a quoted string at line {line_number}" ))); } let inner = &value[1..value.len() - 1]; if inner.trim().is_empty() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -884,7 +915,7 @@ fn parse_text_key(line_number: usize, raw: &str) -> TrustScResult { .strip_prefix("t(") .and_then(|rest| rest.strip_suffix(')')) .ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "text references must use t(\"key\") at line {line_number}" )) })?; @@ -895,7 +926,7 @@ fn parse_system_event(line_number: usize, raw: &str) -> TrustScResult Ok(SystemEvent::NoOp), "SystemEvent.TriggerHalt" => Ok(SystemEvent::TriggerHalt), - other => Err(ValidationError::new(format!( + other => Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported system event `{other}` at line {line_number}" ))), } @@ -905,7 +936,7 @@ fn parse_clock_format(line_number: usize, raw: &str) -> TrustScResult Ok(ClockFormat::TimeSeconds), "DateTimeSeconds" => Ok(ClockFormat::DateTimeSeconds), - other => Err(ValidationError::new(format!( + other => Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported clock format `{other}` at line {line_number}" ))), } @@ -914,12 +945,12 @@ fn parse_clock_format(line_number: usize, raw: &str) -> TrustScResult;` — a plain positive integer (a character count, not pixels). fn parse_max_length(line_number: usize, raw: &str) -> TrustScResult { let value = raw.trim().parse::().map_err(|_| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "max_length must be a positive integer at line {line_number}" )) })?; if value == 0 { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "max_length must be greater than zero at line {line_number}" ))); } @@ -931,7 +962,7 @@ fn parse_max_length(line_number: usize, raw: &str) -> TrustScResult { fn parse_charset(line_number: usize, raw: &str) -> TrustScResult { match raw.trim() { "AsciiText" => Ok(ASCII_TEXT_GLYPH_SET_ID.to_string()), - other => Err(ValidationError::new(format!( + other => Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported charset `{other}` at line {line_number}; approved charsets are: AsciiText" ))), } @@ -945,7 +976,7 @@ fn parse_bracket_list(line_number: usize, field_name: &str, raw: &str) -> TrustS .strip_prefix('[') .and_then(|rest| rest.strip_suffix(']')) .ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must be a [..] list at line {line_number}" )) })?; @@ -956,7 +987,7 @@ fn parse_bracket_list(line_number: usize, field_name: &str, raw: &str) -> TrustS .map(str::to_string) .collect::>(); if entries.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::MISSING_FIELD, format!( "{field_name} must declare at least one entry at line {line_number}" ))); } @@ -984,7 +1015,7 @@ fn parse_image_key(line_number: usize, raw: &str) -> TrustScResult { .strip_prefix("img(") .and_then(|rest| rest.strip_suffix(')')) .ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "Image source must use `img(\"IMAGE-ID\")` at line {line_number}" )) })?; @@ -1001,7 +1032,7 @@ fn parse_dimension(line_number: usize, field_name: &str, raw: &str) -> TrustScRe fn parse_px(line_number: usize, field_name: &str, raw: &str) -> TrustScResult { let px_value = parse_px_allowing_zero(line_number, field_name, raw)?; if px_value == 0 { - return Err(ValidationError::new(format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must be greater than zero at line {line_number}" ))); } @@ -1014,13 +1045,13 @@ fn parse_px_allowing_zero(line_number: usize, field_name: &str, raw: &str) -> Tr raw.trim() .strip_suffix("px") .ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must use a px unit at line {line_number}" )) })? .parse::() .map_err(|_| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must be a non-negative integer px value at line {line_number}" )) }) @@ -1029,7 +1060,7 @@ fn parse_px_allowing_zero(line_number: usize, field_name: &str, raw: &str) -> Tr /// Parses `px, px` — the absolute screen coordinates of a positioned component. fn parse_position(line_number: usize, raw: &str) -> TrustScResult<(u32, u32)> { let (x_raw, y_raw) = raw.split_once(',').ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "position must be `px, px` at line {line_number}" )) })?; @@ -1041,7 +1072,7 @@ fn parse_position(line_number: usize, raw: &str) -> TrustScResult<(u32, u32)> { /// Parses `px, px` — the screen's declared surface pin. fn parse_surface(line_number: usize, raw: &str) -> TrustScResult<(u32, u32)> { let (w_raw, h_raw) = raw.split_once(',').ok_or_else(|| { - ValidationError::new(format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "surface must be `px, px` at line {line_number}" )) })?; @@ -1057,14 +1088,15 @@ fn compile_screen( image_packages: ImagePackages<'_>, ) -> TrustScResult { if options.surface_width == 0 || options.surface_height == 0 { - return Err(ValidationError::new( + return Err(coded( + code::UNREGISTERED, "compile options surface dimensions must be greater than zero", )); } if let Some((declared_width, declared_height)) = screen.declared_surface { if (declared_width, declared_height) != (options.surface_width, options.surface_height) { - return Err(ValidationError::new(format!( + return Err(coded(code::UNREGISTERED, format!( "screen {} declares surface {declared_width}x{declared_height} but the build configured {}x{} — align build.rs .surface(...) with the declaration", screen.id, options.surface_width, options.surface_height ))); @@ -1074,18 +1106,19 @@ fn compile_screen( let content_width = options .surface_width .checked_sub(u32::from(screen.layout.padding) * 2) - .ok_or_else(|| ValidationError::new("layout padding exceeds surface width"))?; + .ok_or_else(|| coded(code::SURFACE_EXCEEDED, "layout padding exceeds surface width"))?; let content_height = options .surface_height .checked_sub(u32::from(screen.layout.padding) * 2) - .ok_or_else(|| ValidationError::new("layout padding exceeds surface height"))?; + .ok_or_else(|| coded(code::SURFACE_EXCEEDED, "layout padding exceeds surface height"))?; let has_rows = screen .items .iter() .any(|item| matches!(item, ScreenItem::Row(_))); if has_rows && screen.layout.kind != LayoutKind::Vertical { - return Err(ValidationError::new( + return Err(coded( + code::FORBIDDEN_CONSTRUCT, "Row containers require a Vertical screen layout", )); } @@ -1224,7 +1257,7 @@ fn compile_screen( height: fixed_dimension(&child, child.height)?, }; if !rect_contains(row_bounds, bounds) { - return Err(ValidationError::new(format!( + return Err(coded(code::LAYOUT_OVERFLOW, format!( "component {} (position {},{}, size {}x{}) escapes its Row {} (bounds {},{} {}x{})", child.id, bounds.x, bounds.y, bounds.width, bounds.height, row.id, row_bounds.x, row_bounds.y, row_bounds.width, @@ -1241,7 +1274,7 @@ fn compile_screen( Dimension::Px(value) => u32::from(value), }; if child_height > row_height { - return Err(ValidationError::new(format!( + return Err(coded(code::LAYOUT_OVERFLOW, format!( "component {} is taller than its Row {}", child.id, row.id ))); @@ -1281,7 +1314,7 @@ fn compile_screen( fn fixed_dimension(node: &NodeDefinition, dimension: Dimension) -> TrustScResult { match dimension { Dimension::Px(value) => Ok(u32::from(value)), - Dimension::Fill => Err(ValidationError::new(format!( + Dimension::Fill => Err(coded(code::LAYOUT_OVERFLOW, format!( "component {}: `position` requires fixed `width`/`height` — Fill is flow-only", node.id ))), @@ -1310,7 +1343,7 @@ fn validate_unique_node_ids(nodes: &[CompiledNodeSpec]) -> TrustScResult<()> { let mut seen = std::collections::BTreeSet::new(); for node in nodes { if !seen.insert(node.id.as_str()) { - return Err(ValidationError::new(format!( + return Err(coded(code::DUPLICATE_NODE_ID, format!( "duplicate node id {} in compiled screen", node.id ))); @@ -1335,7 +1368,7 @@ fn validate_no_overlap( continue; } if rects_strictly_overlap(a.bounds, b.bounds) { - return Err(ValidationError::new(format!( + return Err(coded(code::LAYOUT_OVERFLOW, format!( "component {} (position {},{}, size {}x{}) overlaps component {} (bounds {},{} {}x{}); positioned components must not overlap any other component", a.id, a.bounds.x, a.bounds.y, a.bounds.width, a.bounds.height, b.id, b.bounds.x, b.bounds.y, b.bounds.width, b.bounds.height @@ -1361,7 +1394,7 @@ struct CompileContext<'a, 'p> { impl CompileContext<'_, '_> { fn compile_leaf(&mut self, node: NodeDefinition, bounds: RectSpec) -> TrustScResult<()> { if bounds.x < self.padding || bounds.y < self.padding { - return Err(ValidationError::new(format!( + return Err(coded(code::SURFACE_EXCEEDED, format!( "component {} resolved outside the padded surface", node.id ))); @@ -1370,7 +1403,7 @@ impl CompileContext<'_, '_> { || bounds.y + bounds.height as i32 > self.options.surface_height as i32 - self.padding { - return Err(ValidationError::new(format!( + return Err(coded(code::SURFACE_EXCEEDED, format!( "component {} exceeds the available surface", node.id ))); @@ -1385,7 +1418,7 @@ impl CompileContext<'_, '_> { // compiles always round-trips. if let Some(safety) = &node.safety_critical { if safety.cv_checks.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded(code::MISSING_FIELD, format!( "component {} safety-critical annotation must declare at least one CV check", node.id ))); @@ -1394,21 +1427,21 @@ impl CompileContext<'_, '_> { if let NodeKind::Image { image_id } = &node.kind { let package = self.image_packages.find(image_id).ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "Image {} references unknown image package {image_id}", node.id )) })?; // ADR-014: images render at intrinsic size only — no runtime scaling. if (bounds.width, bounds.height) != (package.width, package.height) { - return Err(ValidationError::new(format!( + return Err(coded(code::UNREGISTERED, format!( "Image {} declares {}x{} but image package {image_id} is {}x{}; images render at intrinsic size only (no scaling)", node.id, bounds.width, bounds.height, package.width, package.height ))); } if let Some(safety) = &node.safety_critical { if safety.cv_checks.contains(&CvCheckKind::ColorHash) { - return Err(ValidationError::new(format!( + return Err(coded(code::UNKNOWN_CV_CHECK, format!( "Image {} cannot use the ColorHash CV check (image-content hashing is not a supported golden check); use Bounds", node.id ))); @@ -1507,7 +1540,7 @@ fn validate_color_tokens(node_id: &str, kind: &NodeKind) -> TrustScResult<()> { .map(|(name, _)| *name) .collect::>() .join(", "); - return Err(ValidationError::new(format!( + return Err(coded(code::UNKNOWN_COLOR_TOKEN, format!( "component {node_id} references unknown theme color token `{token}`; approved tokens are: {approved}" ))); } @@ -1594,7 +1627,7 @@ fn validate_node_text_budget( NodeKind::Panel { .. } | NodeKind::Image { .. } => Ok(()), NodeKind::NumericDisplay { template_id, .. } => { if text_packages.displays.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded(code::UNREGISTERED, format!( "NumericDisplay {} requires a display text package (none was provided to the compiler)", node.id ))); @@ -1621,7 +1654,7 @@ fn validate_static_text_budget( .collect::>(); if locales.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded(code::UNKNOWN_TEXT_KEY, format!( "text key {text_key} for component {} does not exist in the approved text package", node.id ))); @@ -1631,14 +1664,14 @@ fn validate_static_text_budget( let run = text_package .find_run_for_string(text_key, locale) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::TEXT_KEY_MISSING_LOCALE, format!( "text key {text_key} for component {} is missing a compiled run for locale {locale}", node.id )) })?; let run_bounds = measure_text_run_bounds(text_package, run)?; if run_bounds.width() > bounds.width || run_bounds.height() > bounds.height { - return Err(ValidationError::new(format!( + return Err(coded(code::TEXT_BUDGET_EXCEEDED, format!( "text key {text_key} for component {} exceeds bounds in locale {locale}: required width={} height={}, available width={} height={}", node.id, run_bounds.width(), @@ -1664,7 +1697,7 @@ fn validate_clock_budget( let glyph_set = text_package .find_numeric_glyph_set(CLOCK_GLYPH_SET_ID) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "Clock {} requires glyph set {CLOCK_GLYPH_SET_ID} in the approved text package", node.id )) @@ -1682,7 +1715,7 @@ fn validate_clock_budget( measure_glyph_run(node, glyph_set, characters, text_package)?; if required_width > bounds.width || required_height > bounds.height { - return Err(ValidationError::new(format!( + return Err(coded(code::TEXT_BUDGET_EXCEEDED, format!( "Clock {} does not fit its bounds: required width={required_width} height={required_height}, available width={} height={}", node.id, bounds.width, bounds.height ))); @@ -1706,7 +1739,7 @@ fn validate_text_input_budget( let glyph_set = text_package .find_numeric_glyph_set(glyph_set_id) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "TextInput {} requires glyph set {glyph_set_id} in the approved text package", node.id )) @@ -1717,7 +1750,7 @@ fn validate_text_input_budget( .iter() .max_by_key(|entry| entry.advance_x) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "TextInput {} charset glyph set {glyph_set_id} is empty", node.id )) @@ -1727,7 +1760,7 @@ fn validate_text_input_budget( let atlas_glyph = text_package .find_glyph(widest.atlas_index, widest.glyph_id) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "component {} references glyph set {} entry '{}', but atlas index {} glyph {} does not exist in the package — under-measuring height would let an out-of-budget component compile", node.id, glyph_set.id, widest.character, widest.atlas_index, widest.glyph_id )) @@ -1736,7 +1769,7 @@ fn validate_text_input_budget( let required_height = u32::from(atlas_glyph.height); if required_width > bounds.width || required_height > bounds.height { - return Err(ValidationError::new(format!( + return Err(coded(code::TEXT_BUDGET_EXCEEDED, format!( "TextInput {} does not fit its bounds: max_length {max_length} of the widest '{}' glyph requires width={required_width} height={required_height}, available width={} height={}", node.id, widest.character, bounds.width, bounds.height ))); @@ -1754,7 +1787,7 @@ fn validate_numeric_display_budget( display_package: &TextPackage, ) -> TrustScResult<()> { let template = display_package.find_template(template_id).ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "NumericDisplay {} references unknown template {template_id} in the display package", node.id )) @@ -1762,7 +1795,7 @@ fn validate_numeric_display_budget( let glyph_set = display_package .find_numeric_glyph_set(&template.glyph_set_id) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "NumericDisplay {} template references unknown glyph set {}", node.id, template.glyph_set_id )) @@ -1774,7 +1807,7 @@ fn validate_numeric_display_budget( .iter() .max_by_key(|entry| entry.advance_x) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "NumericDisplay {} template glyph set is empty", node.id )) @@ -1788,7 +1821,7 @@ fn validate_numeric_display_budget( .flatten() { let run = display_package.find_run(affix_run_id).ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "NumericDisplay {} template references unknown affix run {affix_run_id}", node.id )) @@ -1799,7 +1832,7 @@ fn validate_numeric_display_budget( } if required_width > bounds.width || required_height > bounds.height { - return Err(ValidationError::new(format!( + return Err(coded(code::TEXT_BUDGET_EXCEEDED, format!( "NumericDisplay {} does not fit its bounds: required width={required_width} height={required_height}, available width={} height={}", node.id, bounds.width, bounds.height ))); @@ -1825,7 +1858,7 @@ fn measure_glyph_run( .iter() .find(|entry| entry.character == *character) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "component {} requires character '{character}' missing from glyph set {}", node.id, glyph_set.id )) @@ -1834,7 +1867,7 @@ fn measure_glyph_run( let atlas_glyph = text_package .find_glyph(entry.atlas_index, entry.glyph_id) .ok_or_else(|| { - ValidationError::new(format!( + coded(code::UNREGISTERED, format!( "component {} references glyph set {} entry '{character}', but atlas index {} glyph {} does not exist in the package — under-measuring height would let an out-of-budget component compile", node.id, glyph_set.id, entry.atlas_index, entry.glyph_id )) @@ -1882,11 +1915,12 @@ fn resolve_axis_sizes( let total_spacing = spacing as u32 * dimensions.len().saturating_sub(1) as u32; let available = total_fill_space .checked_sub(fixed_total + total_spacing) - .ok_or_else(|| ValidationError::new("layout exceeds available surface"))?; + .ok_or_else(|| coded(code::SURFACE_EXCEEDED, "layout exceeds available surface"))?; let fill_size = if fill_count == 0 { 0 } else { available / fill_count }; if fill_count > 0 && fill_size == 0 { - return Err(ValidationError::new( + return Err(coded( + code::LAYOUT_OVERFLOW, "Fill layout items do not have enough remaining space", )); } @@ -3417,6 +3451,118 @@ Screen InteractivePanel { } } + /// Wraps `body` in the smallest screen that reaches component parsing. + fn screen_with(body: &str) -> String { + format!( + "Screen Broken {{\n\ + layout: Vertical {{ spacing: 8px; padding: 0px; }}\n\ + {body}\n\ + }}\n" + ) + } + + #[test] + fn parse_time_diagnostics_carry_their_registered_code() { + // The code is assigned where the condition is detected, so this table pins raise site to + // identity. It is the regression guard for the message-matching classifier this replaced: + // rewording any message below must not change the code it reports. + let cases: &[(&str, &str, &str)] = &[ + ( + "unknown component", + "Bogus {\nid: x;\n}", + code::UNKNOWN_COMPONENT, + ), + ( + "unknown field", + "CriticalButton {\nbogus_prop: 1;\n}", + code::UNKNOWN_FIELD, + ), + ( + "missing field", + "CriticalButton {\nid: x;\n}", + code::MISSING_FIELD, + ), + ( + "nested row", + "Row {\nid: outer;\nheight: 80px;\nRow {\nid: inner;\nheight: 40px;\n}\n}", + code::NESTED_ROW, + ), + ( + "safety annotation on a Row", + "@safety_critical(cv_check: [Bounds])\nRow {\nid: outer;\nheight: 80px;\n}", + code::FORBIDDEN_CONSTRUCT, + ), + ( + "unknown CV check", + "@safety_critical(cv_check: [Bogus])\nLabel {\nid: x;\n}", + code::UNKNOWN_CV_CHECK, + ), + ( + "identifier with a space", + "Label {\nid: not an id;\n}", + code::UNEXPECTED_TOKEN, + ), + ( + "position with a Fill dimension", + "Label {\nid: x;\nwidth: Fill;\nheight: 40px;\nposition: 0px, 0px;\n}", + code::LAYOUT_OVERFLOW, + ), + ]; + + for (what, body, expected) in cases { + let source = screen_with(body); + let diagnostics = + parse_medui_source(&source).expect_err(&format!("{what} should not parse")); + assert_eq!(diagnostics.len(), 1, "{what}"); + assert_eq!( + diagnostics[0].code, *expected, + "{what}: message was {:?}", + diagnostics[0].message + ); + } + } + + #[test] + fn compile_time_errors_carry_their_registered_code() { + // `MEDUI-E014` and `MEDUI-E030` are raised after parsing, so they are reached through a + // full compile rather than `parse_medui_source`. Going through the string-returning entry + // point also covers the single-diagnostic path that must not flatten the identity. + let duplicate = POSITIONED_MEDUI.replace( + " id: sedation-index;", + " id: topbar-background;", + ); + assert_eq!( + compile_positioned(&duplicate) + .expect_err("duplicate node id must fail") + .code(), + Some(code::DUPLICATE_NODE_ID) + ); + + let unknown_token = POSITIONED_MEDUI.replace( + " color: Theme.Colors.Title;", + " color: Theme.Colors.Titel;", + ); + assert_eq!( + compile_positioned(&unknown_token) + .expect_err("unknown theme color token must fail") + .code(), + Some(code::UNKNOWN_COLOR_TOKEN) + ); + } + + #[test] + fn every_raise_site_declares_a_code() { + // The needle is assembled at runtime so this assertion does not match itself in the + // source text it scans. + let needle = concat!("ValidationError", "::new("); + let occurrences = include_str!("lib.rs").matches(needle).count(); + assert_eq!( + occurrences, 0, + "an untagged raise site would report the `code::UNEXPECTED_TOKEN` fallback instead of \ + its own identity; raise it through `coded(code::…, …)` instead" + ); + } + #[test] fn diagnostics_carry_the_source_line_for_broken_inputs() { // Every case below is a pure syntax error caught by `parse_screen` itself, where a line @@ -3467,6 +3613,17 @@ Screen InteractivePanel { } } + #[test] + fn lone_quote_returns_a_positioned_diagnostic_instead_of_panicking() { + let error = parse_quoted(7, "requirement", "\"") + .expect_err("a lone quote is not a delimited string"); + let diagnostic = Diagnostic::from_validation_error(&error); + + assert_eq!(diagnostic.code, code::UNEXPECTED_TOKEN); + assert_eq!(diagnostic.line, Some(7)); + assert!(diagnostic.message.contains("must be a quoted string")); + } + #[test] fn diagnostic_has_no_line_for_compile_time_only_errors() { let source = "Screen Broken {\n\ diff --git a/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs new file mode 100644 index 0000000..ccdfa87 --- /dev/null +++ b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs @@ -0,0 +1,680 @@ +//! Runs the pinned `Compliatory/MedUI` conformance cases against this implementation. +//! +//! Every expectation is read from the pinned checkout's `case.json` — never from a hand-written +//! copy here — so a change to the shared contract shows up as a failure rather than as a silent +//! divergence between the two repositories. +//! +//! `MEDUI-DEC-005` requires that a consumer "must not silently skip a claimed phase". Two rules +//! follow from that and are enforced below: +//! +//! - CI, which does have the pinned checkout, *fails* when it is missing rather than skipping. +//! A developer without the checkout gets an explicit skip notice; `CI=1` turns that into a +//! hard error, so the evidence-producing run can never be vacuous. +//! - Every capability claimed by `medui-conformance.toml` must be backed by at least one pinned +//! case that actually executed, and the claim must name a phase this harness knows how to +//! observe. Claiming a phase with no adapter fails the suite instead of passing silently. +//! - A pinned position is checked against the precision the manifest declares, per +//! `spec/diagnostics.md`. A phase claimed at reduced precision is still claimed, and reporting +//! more position than declared is a failure, so precision cannot move without a manifest edit. +//! +//! Only the parse phase is observable here, which is why `capabilities` claims `syntax` alone. +//! Claiming `semantics`, `layout`, or `safety` additionally requires driving +//! `compile_medui_source` with the text and image packages a case declares in `inputs`, and this +//! harness deliberately refuses such a claim until that adapter exists. + +use std::{ + collections::BTreeSet, + fs, + path::{Path, PathBuf}, + process::Command, +}; + +use trustsc_ui_dsl_authoring::{Diagnostic, parse_medui_source}; + +/// Phases this harness can genuinely observe. Anything else claimed in `medui-conformance.toml` +/// is a claim without an adapter behind it. +const RUNNABLE_CAPABILITIES: &[&str] = &["syntax"]; + +#[test] +fn pinned_shared_conformance_cases() { + let manifest = Manifest::read(&repo_root().join("medui-conformance.toml")); + + for capability in &manifest.capabilities { + assert!( + RUNNABLE_CAPABILITIES.contains(&capability.as_str()), + "medui-conformance.toml claims `{capability}`, but this harness can only observe \ + {RUNNABLE_CAPABILITIES:?}. Add the adapter that checks that phase's normalized \ + observations before claiming it." + ); + } + + let Some(root) = conformance_root() else { + return; + }; + assert_checkout_matches(&root, &manifest.commit); + + let cases = load_cases(&root); + assert!( + !cases.is_empty(), + "no conformance cases found under {}; is MEDUI_CONFORMANCE_DIR pointing at a \ + Compliatory/MedUI checkout?", + root.display() + ); + + let mut executed = BTreeSet::new(); + let mut skipped = Vec::new(); + for case in &cases { + if manifest.capabilities.contains(&case.phase) { + run_case(case, &manifest); + executed.insert(case.phase.clone()); + } else { + skipped.push(format!("{} ({})", case.id, case.phase)); + } + } + + for capability in &manifest.capabilities { + assert!( + executed.contains(capability), + "capability `{capability}` is claimed, but no case in the pinned contract exercised \ + it. Either the pin is wrong or the claim is unsupported." + ); + } + + eprintln!( + "MedUI conformance: {} case(s) at {}; claimed {:?}; unclaimed and not asserted: {}", + cases.len(), + manifest.commit, + manifest.capabilities, + if skipped.is_empty() { + "none".to_string() + } else { + skipped.join(", ") + } + ); +} + +fn run_case(case: &Case, manifest: &Manifest) { + let source = fs::read_to_string(&case.source).unwrap_or_else(|error| { + panic!("{}: source {:?} should read: {error}", case.id, case.source) + }); + + match parse_medui_source(&source) { + Ok(_) => assert!( + case.expect_valid, + "{}: this implementation accepted a source the pinned contract rejects", + case.id + ), + Err(diagnostics) => { + assert!( + !case.expect_valid, + "{}: this implementation rejected a source the pinned contract accepts: {:?}", + case.id, diagnostics + ); + assert_diagnostics(case, &diagnostics, manifest); + } + } +} + +fn assert_diagnostics(case: &Case, actual: &[Diagnostic], manifest: &Manifest) { + assert_eq!( + actual.len(), + case.expected.len(), + "{}: expected {} diagnostic(s), got {:?}", + case.id, + case.expected.len(), + actual + ); + + for (expected, actual) in case.expected.iter().zip(actual) { + assert_eq!( + actual.code, expected.code, + "{}: diagnostic code (message was {:?})", + case.id, actual.message + ); + // `spec/diagnostics.md`, "Positions in conformance cases": a pinned position is matched + // as far as the declared precision goes, and reporting more than was declared fails. The + // declaration is checked rather than tolerated, so precision cannot move silently in + // either direction. `0` means unknown, which is how `None` maps. + match manifest.positions { + Positions::Full => { + assert_eq!( + i64::from(actual.line.unwrap_or(0)), + expected.line, + "{}: diagnostic line", + case.id + ); + assert_eq!( + i64::from(actual.column.unwrap_or(0)), + expected.column, + "{}: diagnostic column", + case.id + ); + } + Positions::LineOnly => { + assert_eq!( + i64::from(actual.line.unwrap_or(0)), + expected.line, + "{}: diagnostic line", + case.id + ); + assert!( + actual.column.is_none(), + "{}: medui-conformance.toml declares positions = \"line-only\", but the parser \ + reported column {:?}. Raise the declaration to \"full\" so the pinned column \ + {} is checked.", + case.id, + actual.column, + expected.column + ); + } + Positions::None => assert!( + actual.line.is_none() && actual.column.is_none(), + "{}: medui-conformance.toml declares positions = \"none\", but the parser \ + reported {:?}:{:?}. Raise the declaration so the pinned position {}:{} is \ + checked.", + case.id, + actual.line, + actual.column, + expected.line, + expected.column + ), + } + } +} + +fn repo_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..") +} + +/// The pinned checkout, or `None` when a developer is running without one. Absent in CI this is a +/// hard failure: a claimed phase is never silently skipped where the evidence is produced. +fn conformance_root() -> Option { + match std::env::var_os("MEDUI_CONFORMANCE_DIR") { + Some(value) => Some(PathBuf::from(value)), + None if std::env::var_os("CI").is_some() => panic!( + "MEDUI_CONFORMANCE_DIR is unset in CI. The pinned Compliatory/MedUI checkout is \ + required to substantiate the capabilities claimed in medui-conformance.toml." + ), + None => { + eprintln!( + "MedUI conformance: SKIPPED — set MEDUI_CONFORMANCE_DIR to a checkout of the \ + commit pinned in medui-conformance.toml to run the shared cases locally." + ); + None + } + } +} + +/// Verifies that the cases came from the commit named in the conformance report. Using Git to +/// resolve `HEAD` also handles worktrees, symbolic refs, and packed refs without duplicating +/// Git's repository-layout rules here. +fn assert_checkout_matches(root: &Path, commit: &str) { + let output = Command::new("git") + .arg("-C") + .arg(root) + .args(["rev-parse", "HEAD"]) + .output() + .unwrap_or_else(|error| { + panic!( + "cannot run git to verify the MedUI checkout at {}: {error}", + root.display() + ) + }); + assert!( + output.status.success(), + "cannot resolve HEAD for the MedUI checkout at {}: {}", + root.display(), + String::from_utf8_lossy(&output.stderr).trim() + ); + let resolved = + String::from_utf8(output.stdout).expect("the MedUI checkout's commit id should be UTF-8"); + let resolved = resolved.trim(); + assert!( + resolved.eq_ignore_ascii_case(commit), + "MEDUI_CONFORMANCE_DIR is at {resolved}, but medui-conformance.toml pins {commit}" + ); +} + +// ------------------------------------------------------------------------------------------- +// medui-conformance.toml +// ------------------------------------------------------------------------------------------- + +/// The declared diagnostic position precision from `spec/diagnostics.md`. +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +enum Positions { + /// Line and exact 1-based UTF-8 byte column; both pinned positions are checked. + Full, + /// Line only; the pinned line is checked and every column is required to be absent. + LineOnly, + /// Neither; both are required to be absent. + None, +} + +#[derive(Debug)] +struct Manifest { + commit: String, + capabilities: Vec, + positions: Positions, +} + +impl Manifest { + /// A deliberately strict reader for this repository's own six-key manifest rather than a + /// general TOML parser: `crates/` takes no third-party dependencies, and anything this does + /// not recognise is an error instead of a silently ignored line. + fn read(path: &Path) -> Manifest { + let text = fs::read_to_string(path) + .unwrap_or_else(|error| panic!("{} should read: {error}", path.display())); + + let mut commit = None; + let mut capabilities = None; + let mut positions = None; + + for (index, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (key, value) = line.split_once(" = ").unwrap_or_else(|| { + panic!( + "{}:{}: expected `key = value`, got {line:?}", + path.display(), + index + 1 + ) + }); + match key { + "commit" => commit = Some(unquote(path, index, value).to_string()), + "capabilities" => capabilities = Some(string_array(path, index, value)), + "positions" => { + positions = Some(match unquote(path, index, value) { + "full" => Positions::Full, + "line-only" => Positions::LineOnly, + "none" => Positions::None, + other => panic!( + "{}:{}: positions must be \"full\", \"line-only\" or \"none\", got \ + {other:?}", + path.display(), + index + 1 + ), + }) + } + "repository" | "version" => {} + other => panic!( + "{}:{}: unknown key {other:?}; update this harness when the manifest grows a key", + path.display(), + index + 1 + ), + } + } + + let commit = commit.unwrap_or_else(|| panic!("{} must pin a `commit`", path.display())); + assert!( + commit.len() == 40 && commit.bytes().all(|byte| byte.is_ascii_hexdigit()), + "{} must pin a 40-character commit SHA, got {commit:?}", + path.display() + ); + let capabilities = capabilities + .unwrap_or_else(|| panic!("{} must declare `capabilities`", path.display())); + assert!( + !capabilities.is_empty(), + "{} declares no capabilities, so this suite would assert nothing. Remove the pin or \ + claim a phase.", + path.display() + ); + + Manifest { + commit, + capabilities, + positions: positions + .unwrap_or_else(|| panic!("{} must declare `positions`", path.display())), + } + } +} + +fn unquote<'a>(path: &Path, index: usize, value: &'a str) -> &'a str { + value + .strip_prefix('"') + .and_then(|rest| rest.strip_suffix('"')) + .unwrap_or_else(|| { + panic!( + "{}:{}: expected a quoted string, got {value:?}", + path.display(), + index + 1 + ) + }) +} + +fn string_array(path: &Path, index: usize, value: &str) -> Vec { + let inner = value + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix(']')) + .unwrap_or_else(|| { + panic!( + "{}:{}: expected an array, got {value:?}", + path.display(), + index + 1 + ) + }); + inner + .split(',') + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .map(|entry| unquote(path, index, entry).to_string()) + .collect() +} + +// ------------------------------------------------------------------------------------------- +// Conformance cases +// ------------------------------------------------------------------------------------------- + +#[derive(Debug)] +struct Case { + id: String, + phase: String, + source: PathBuf, + expect_valid: bool, + expected: Vec, +} + +#[derive(Debug)] +struct ExpectedDiagnostic { + code: String, + line: i64, + column: i64, +} + +fn load_cases(root: &Path) -> Vec { + let mut paths = Vec::new(); + collect_case_files(&root.join("conformance"), &mut paths); + paths.sort(); + paths.iter().map(|path| Case::read(path)).collect() +} + +fn collect_case_files(directory: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(directory) else { + return; + }; + for entry in entries { + let path = entry.expect("directory entry should read").path(); + if path.is_dir() { + collect_case_files(&path, out); + } else if path.file_name().is_some_and(|name| name == "case.json") { + out.push(path); + } + } +} + +impl Case { + fn read(path: &Path) -> Case { + let text = fs::read_to_string(path) + .unwrap_or_else(|error| panic!("{} should read: {error}", path.display())); + let json = Json::parse(&text, path); + + let id = json.get(path, "id").string(path).to_string(); + let phase = json.get(path, "phase").string(path).to_string(); + let source = json.get(path, "source").string(path).to_string(); + let expected = json.get(path, "expected"); + + assert!( + !source.contains('/') && source.ends_with(".medui"), + "{}: source must be a sibling `.medui` file, got {source:?}", + path.display() + ); + // `case.schema.json` binds the phase to the directory that contains the case. + let directory_phase = path + .parent() + .and_then(Path::parent) + .and_then(Path::file_name) + .and_then(|name| name.to_str()) + .unwrap_or_default(); + assert_eq!( + phase, + directory_phase, + "{}: declared phase does not match its directory", + path.display() + ); + + Case { + id, + phase, + source: path.parent().expect("case has a parent").join(source), + expect_valid: expected.get(path, "valid").boolean(path), + expected: expected + .get(path, "diagnostics") + .array(path) + .iter() + .map(|entry| ExpectedDiagnostic { + code: entry.get(path, "code").string(path).to_string(), + line: entry.get(path, "line").integer(path), + column: entry.get(path, "column").integer(path), + }) + .collect(), + } + } +} + +// ------------------------------------------------------------------------------------------- +// A strict reader for the JSON subset `schemas/case.schema.json` permits +// ------------------------------------------------------------------------------------------- +// +// `crates/` takes no third-party dependencies (AGENTS.md trust zones), so rather than pull +// `serde_json` into a governed crate this reads the small, schema-constrained shape the pinned +// cases use. It is strict on purpose: escapes, floats, and `null` are rejected outright, so a +// case this cannot represent fails loudly instead of being silently misread into a vacuous pass. + +#[derive(Debug, Clone, PartialEq)] +enum Json { + Bool(bool), + Int(i64), + Str(String), + Arr(Vec), + Obj(Vec<(String, Json)>), +} + +impl Json { + fn parse(text: &str, path: &Path) -> Json { + let bytes = text.as_bytes(); + let mut at = 0usize; + let value = parse_value(bytes, &mut at, path); + skip_whitespace(bytes, &mut at); + assert_eq!( + at, + bytes.len(), + "{}: trailing content after the top-level JSON value", + path.display() + ); + value + } + + fn get(&self, path: &Path, key: &str) -> &Json { + match self { + Json::Obj(members) => members + .iter() + .find(|(name, _)| name == key) + .map(|(_, value)| value) + .unwrap_or_else(|| panic!("{}: missing required member {key:?}", path.display())), + other => panic!("{}: expected an object, got {other:?}", path.display()), + } + } + + fn string(&self, path: &Path) -> &str { + match self { + Json::Str(value) => value, + other => panic!("{}: expected a string, got {other:?}", path.display()), + } + } + + fn integer(&self, path: &Path) -> i64 { + match self { + Json::Int(value) => *value, + other => panic!("{}: expected an integer, got {other:?}", path.display()), + } + } + + fn boolean(&self, path: &Path) -> bool { + match self { + Json::Bool(value) => *value, + other => panic!("{}: expected a boolean, got {other:?}", path.display()), + } + } + + fn array(&self, path: &Path) -> &[Json] { + match self { + Json::Arr(values) => values, + other => panic!("{}: expected an array, got {other:?}", path.display()), + } + } +} + +fn skip_whitespace(bytes: &[u8], at: &mut usize) { + while *at < bytes.len() && bytes[*at].is_ascii_whitespace() { + *at += 1; + } +} + +fn expect_byte(bytes: &[u8], at: &mut usize, byte: u8, path: &Path) { + skip_whitespace(bytes, at); + assert!( + *at < bytes.len() && bytes[*at] == byte, + "{}: expected {:?} at byte {at}", + path.display(), + byte as char + ); + *at += 1; +} + +fn parse_value(bytes: &[u8], at: &mut usize, path: &Path) -> Json { + skip_whitespace(bytes, at); + assert!( + *at < bytes.len(), + "{}: unexpected end of input", + path.display() + ); + match bytes[*at] { + b'{' => parse_object(bytes, at, path), + b'[' => parse_array(bytes, at, path), + b'"' => Json::Str(parse_string(bytes, at, path)), + b't' | b'f' => parse_bool(bytes, at, path), + b'-' | b'0'..=b'9' => parse_integer(bytes, at, path), + other => panic!( + "{}: unsupported JSON value starting with {:?} at byte {at}", + path.display(), + other as char + ), + } +} + +fn parse_object(bytes: &[u8], at: &mut usize, path: &Path) -> Json { + expect_byte(bytes, at, b'{', path); + let mut members = Vec::new(); + skip_whitespace(bytes, at); + if *at < bytes.len() && bytes[*at] == b'}' { + *at += 1; + return Json::Obj(members); + } + loop { + skip_whitespace(bytes, at); + let key = parse_string(bytes, at, path); + expect_byte(bytes, at, b':', path); + let value = parse_value(bytes, at, path); + assert!( + !members + .iter() + .any(|(name, _): &(String, Json)| name == &key), + "{}: duplicate member {key:?}", + path.display() + ); + members.push((key, value)); + skip_whitespace(bytes, at); + match bytes.get(*at) { + Some(b',') => *at += 1, + Some(b'}') => { + *at += 1; + return Json::Obj(members); + } + other => panic!( + "{}: expected ',' or '}}' in object, got {other:?} at byte {at}", + path.display() + ), + } + } +} + +fn parse_array(bytes: &[u8], at: &mut usize, path: &Path) -> Json { + expect_byte(bytes, at, b'[', path); + let mut values = Vec::new(); + skip_whitespace(bytes, at); + if *at < bytes.len() && bytes[*at] == b']' { + *at += 1; + return Json::Arr(values); + } + loop { + values.push(parse_value(bytes, at, path)); + skip_whitespace(bytes, at); + match bytes.get(*at) { + Some(b',') => *at += 1, + Some(b']') => { + *at += 1; + return Json::Arr(values); + } + other => panic!( + "{}: expected ',' or ']' in array, got {other:?} at byte {at}", + path.display() + ), + } + } +} + +fn parse_string(bytes: &[u8], at: &mut usize, path: &Path) -> String { + expect_byte(bytes, at, b'"', path); + let start = *at; + while *at < bytes.len() && bytes[*at] != b'"' { + assert_ne!( + bytes[*at], + b'\\', + "{}: escape sequences are not supported by this reader", + path.display() + ); + *at += 1; + } + assert!(*at < bytes.len(), "{}: unterminated string", path.display()); + let value = std::str::from_utf8(&bytes[start..*at]) + .unwrap_or_else(|error| panic!("{}: string is not UTF-8: {error}", path.display())) + .to_string(); + *at += 1; + value +} + +fn parse_bool(bytes: &[u8], at: &mut usize, path: &Path) -> Json { + if bytes[*at..].starts_with(b"true") { + *at += 4; + Json::Bool(true) + } else if bytes[*at..].starts_with(b"false") { + *at += 5; + Json::Bool(false) + } else { + panic!("{}: invalid literal at byte {at}", path.display()) + } +} + +fn parse_integer(bytes: &[u8], at: &mut usize, path: &Path) -> Json { + let start = *at; + if bytes[*at] == b'-' { + *at += 1; + } + while *at < bytes.len() && bytes[*at].is_ascii_digit() { + *at += 1; + } + // `case.schema.json` uses integers only; a float here means the case says something this + // reader would otherwise round away. + assert!( + !matches!(bytes.get(*at), Some(b'.') | Some(b'e') | Some(b'E')), + "{}: non-integer numbers are not supported by this reader", + path.display() + ); + let text = std::str::from_utf8(&bytes[start..*at]).expect("digits are ASCII"); + Json::Int( + text.parse().unwrap_or_else(|error| { + panic!("{}: invalid integer {text:?}: {error}", path.display()) + }), + ) +} diff --git a/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md b/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md index a6783c4..4f4554e 100644 --- a/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md +++ b/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md @@ -4,6 +4,13 @@ - **Date:** 2026-05-31 - **Related issues:** #6, #7, #8 +## Shared decision identity + +This TrustSC decision implements +[`MEDUI-DEC-001`](https://github.com/Compliatory/MedUI/blob/c8cc45ecec2f2dfd84940b9efc17c613e691cc0d/decisions/MEDUI-DEC-001-build-time-compilation.md) +and the closed-language part of `MEDUI-DEC-002`. ADR-008 remains the permanent local identity; +cross-repository citations use the shared identifier. + ## Context `TrustSC` needs a declarative UI authoring language for safety-critical medical screens without introducing runtime interpretation, dynamic layout solving, or uncontrolled text rendering into the regulated runtime path. diff --git a/docs/adr/ADR-009-medui-compilation-and-generated-artifacts.md b/docs/adr/ADR-009-medui-compilation-and-generated-artifacts.md index 5c78e27..e00fddf 100644 --- a/docs/adr/ADR-009-medui-compilation-and-generated-artifacts.md +++ b/docs/adr/ADR-009-medui-compilation-and-generated-artifacts.md @@ -4,6 +4,13 @@ - **Date:** 2026-05-31 - **Related issues:** #6, #7, #8 +## Shared decision identity + +This record is TrustSC's Rust realization of +[`MEDUI-DEC-003`](https://github.com/Compliatory/MedUI/blob/c8cc45ecec2f2dfd84940b9efc17c613e691cc0d/decisions/MEDUI-DEC-003-compiled-screen-semantics.md). +The shared record defines compiled meaning; this ADR remains authoritative for generated Rust and +TrustSC's build integration. + ## Context The DSL must produce evidence that can be audited, diffed, and consumed by runtime code without parsing the original `.medui` source. diff --git a/docs/adr/ADR-011-medui-safety-monitor-and-vulkan-viewport-contract.md b/docs/adr/ADR-011-medui-safety-monitor-and-vulkan-viewport-contract.md index a1ed134..6ede7bf 100644 --- a/docs/adr/ADR-011-medui-safety-monitor-and-vulkan-viewport-contract.md +++ b/docs/adr/ADR-011-medui-safety-monitor-and-vulkan-viewport-contract.md @@ -1,5 +1,9 @@ # ADR-011: MedUI safety-monitor and VulkanViewport contract +This local record implements the safety annotation and golden-reference rules of +[`MEDUI-DEC-004`](https://github.com/Compliatory/MedUI/blob/c8cc45ecec2f2dfd84940b9efc17c613e691cc0d/decisions/MEDUI-DEC-004-safety-and-goldens.md). +Its ADR number remains permanent and local. + - **Status:** Accepted - **Date:** 2026-05-31 - **Related issues:** #6, #7, #8 diff --git a/docs/dsl/overview.md b/docs/dsl/overview.md index 80170cf..bc9f511 100644 --- a/docs/dsl/overview.md +++ b/docs/dsl/overview.md @@ -1,5 +1,10 @@ # MedUI DSL overview +The implementation-neutral contract is versioned in +[`Compliatory/MedUI`](https://github.com/Compliatory/MedUI) and pinned by the repository-root +`medui-conformance.toml`. This directory documents TrustSC's Rust build, runtime, rendering, and +evidence integration; where portable language rules differ, the pinned shared contract wins. + The MedUI DSL is a deterministic build-time language for authored medical UI screens in `TrustSC`. ## Goals diff --git a/docs/governance/soup-register.toml b/docs/governance/soup-register.toml index c9359e8..a4bdc23 100644 --- a/docs/governance/soup-register.toml +++ b/docs/governance/soup-register.toml @@ -53,9 +53,9 @@ classification = "SOUP" supplier = "crates.io / serde-rs maintainers" repository = "https://github.com/serde-rs/json" license = "MIT OR Apache-2.0" -usage = "Emits deterministic host-side package.json and report.json artifacts for review and reproducibility checks, and parses approved package.json inputs into generated Rust source during trustsc builds. Also parses the safetensors container header in crates/trustsc-ml-authoring (ADR-017 §6, avoiding a dedicated safetensors crate dependency), and parses/emits ML model package.json/report.json evidence in tools/trustsc-ml-baker and crates/trustsc-build model codegen, and shader package.json/report.json evidence in tools/trustsc-shader-baker (ADR-012). Also serializes the MedUI Studio server's `/api/screens` JSON response body in tools/trustsc-medui-studio (ADR-022)." -integration_path = "tools/trustsc-font-baker, crates/trustsc/build.rs, crates/trustsc-ml-authoring, tools/trustsc-ml-baker, crates/trustsc-build (model codegen), tools/trustsc-shader-baker, tools/trustsc-medui-studio" -pinned_by = ["tools/trustsc-font-baker/Cargo.toml", "crates/trustsc/Cargo.toml", "crates/trustsc-ml-authoring/Cargo.toml", "tools/trustsc-ml-baker/Cargo.toml", "crates/trustsc-build/Cargo.toml", "tools/trustsc-shader-baker/Cargo.toml", "tools/trustsc-medui-studio/Cargo.toml", "Cargo.lock"] +usage = "Emits deterministic host-side package.json and report.json artifacts for review and reproducibility checks, and parses approved package.json inputs into generated Rust source during trustsc builds. Also parses the safetensors container header in crates/trustsc-ml-authoring (ADR-017 §6, avoiding a dedicated safetensors crate dependency), and parses/emits ML model package.json/report.json evidence in tools/trustsc-ml-baker and crates/trustsc-build model codegen, and shader package.json/report.json evidence in tools/trustsc-shader-baker (ADR-012). Also serializes the MedUI Studio server's `/api/screens` JSON response body in tools/trustsc-medui-studio (ADR-022). Also serializes `trustsc-medui-check --format=json`, which emits the shared MedUI finding envelope pinned by medui-conformance.toml so a consumer keys off the stable MEDUI-E### identity rather than parsing human text." +integration_path = "tools/trustsc-font-baker, crates/trustsc/build.rs, crates/trustsc-ml-authoring, tools/trustsc-ml-baker, crates/trustsc-build (model codegen), tools/trustsc-shader-baker, tools/trustsc-medui-studio, tools/trustsc-medui-check" +pinned_by = ["tools/trustsc-font-baker/Cargo.toml", "crates/trustsc/Cargo.toml", "crates/trustsc-ml-authoring/Cargo.toml", "tools/trustsc-ml-baker/Cargo.toml", "crates/trustsc-build/Cargo.toml", "tools/trustsc-shader-baker/Cargo.toml", "tools/trustsc-medui-studio/Cargo.toml", "tools/trustsc-medui-check/Cargo.toml", "Cargo.lock"] runtime_deployment = false yocto_target_dependency = false support_model = "Community-maintained crate; no medical-device qualification or vendor support agreement." diff --git a/medui-conformance.toml b/medui-conformance.toml new file mode 100644 index 0000000..da887a4 --- /dev/null +++ b/medui-conformance.toml @@ -0,0 +1,15 @@ +repository = "https://github.com/Compliatory/MedUI" +version = "0.1.0-candidate" +# The single source of truth for the pin: CI derives its `actions/checkout` ref from this line, +# and `crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs` reads the same file, so the +# workflow and the harness cannot drift apart. +commit = "c8cc45ecec2f2dfd84940b9efc17c613e691cc0d" +# The implementation already has richer local behavior, but only syntax is claimed until each +# shared phase has a complete adapter that checks its normalized observations. +capabilities = ["syntax"] +# Diagnostic position precision, per `spec/diagnostics.md`. `parse_screen` is line-oriented and +# trims each line before matching, so no column survives to `Diagnostic::column`. The contract +# checks this declaration in both directions: pinned lines are matched exactly, pinned columns are +# required to be absent, and a diagnostic that started carrying one would fail the suite until +# this is raised to `full`. +positions = "line-only" diff --git a/tools/trustsc-medui-check/Cargo.toml b/tools/trustsc-medui-check/Cargo.toml index fb9ef23..65f8a72 100644 --- a/tools/trustsc-medui-check/Cargo.toml +++ b/tools/trustsc-medui-check/Cargo.toml @@ -7,3 +7,4 @@ publish = false [dependencies] trustsc-ui-dsl-authoring = { version = "0.1.0", path = "../../crates/trustsc-ui-dsl-authoring" } trustsc = { version = "0.1.0", path = "../../crates/trustsc" } +serde_json = "1.0.150" diff --git a/tools/trustsc-medui-check/src/main.rs b/tools/trustsc-medui-check/src/main.rs index cd9aacf..cf17ecf 100644 --- a/tools/trustsc-medui-check/src/main.rs +++ b/tools/trustsc-medui-check/src/main.rs @@ -3,11 +3,16 @@ //! //! Host tooling only (ADR-005 trust zones): a workspace member under `tools/`, never linked into //! any `crates/`/`adapters/` code that ships to a device. +//! +//! `--format=json` emits the shared finding envelope from the pinned `Compliatory/MedUI` contract +//! (`schemas/diagnostic.schema.json`) so an agent or CI step keys off the stable `MEDUI-E###` +//! identity rather than parsing the human text, which the contract says may be reworded. use std::process::ExitCode; use trustsc_ui_dsl_authoring::{ - CompileOptions, Diagnostic, ImagePackages, TextPackages, compile_screen_definition, parse_medui_source, + CompileOptions, Diagnostic, ImagePackages, Severity, TextPackages, code, + compile_screen_definition, parse_medui_source, }; /// Matches the fallback every other tool in this repo uses for a screen with no `surface:` pin @@ -16,12 +21,43 @@ use trustsc_ui_dsl_authoring::{ /// against the same conventional default. const DEFAULT_SURFACE: (u32, u32) = (800, 480); +/// How diagnostics are rendered. `Text` is for a human at a terminal; `Json` is the shared +/// envelope, which is what a machine should read. +#[derive(Clone, Copy, Eq, PartialEq)] +enum Format { + Text, + Json, +} + fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); - let path = match args.as_slice() { - [path] => path, + let mut format = Format::Text; + let mut positional = Vec::new(); + let mut argument_error = None; + for arg in &args { + match arg.as_str() { + "--format=text" => format = Format::Text, + "--format=json" => format = Format::Json, + other if other.starts_with("--") => { + argument_error.get_or_insert_with(|| format!("unknown option {other}")); + } + other => positional.push(other), + } + } + if let Some(message) = argument_error { + report_early_failure(&message, "", code::UNEXPECTED_TOKEN, format); + return ExitCode::from(2); + } + let path = match positional.as_slice() { + [path] => *path, _ => { - eprintln!("usage: trustsc-medui-check "); + let message = "usage: trustsc-medui-check [--format=text|json] "; + match format { + Format::Text => eprintln!("{message}"), + Format::Json => { + report_early_failure(message, "", code::UNEXPECTED_TOKEN, format) + } + } return ExitCode::from(2); } }; @@ -29,7 +65,12 @@ fn main() -> ExitCode { let source = match std::fs::read_to_string(path) { Ok(source) => source, Err(error) => { - eprintln!("trustsc-medui-check: failed to read {path}: {error}"); + report_early_failure( + &format!("failed to read {path}: {error}"), + path, + code::SOURCE_UNREADABLE, + format, + ); return ExitCode::FAILURE; } }; @@ -37,7 +78,7 @@ fn main() -> ExitCode { let screen = match parse_medui_source(&source) { Ok(screen) => screen, Err(diagnostics) => { - print_diagnostics(&diagnostics); + report(&diagnostics, path, format); return ExitCode::FAILURE; } }; @@ -45,14 +86,24 @@ fn main() -> ExitCode { let standard_package = match trustsc::default_standard_text_package() { Ok(package) => package, Err(error) => { - eprintln!("trustsc-medui-check: failed to load the standard text package: {error}"); + report_early_failure( + &format!("failed to load the standard text package: {error}"), + path, + code::UNREGISTERED, + format, + ); return ExitCode::FAILURE; } }; let display_packages = match trustsc::default_display_text_packages() { Ok(packages) => packages, Err(error) => { - eprintln!("trustsc-medui-check: failed to load the display text packages: {error}"); + report_early_failure( + &format!("failed to load the display text packages: {error}"), + path, + code::UNREGISTERED, + format, + ); return ExitCode::FAILURE; } }; @@ -60,7 +111,12 @@ fn main() -> ExitCode { let image_packages = match trustsc::default_image_packages() { Ok(packages) => packages, Err(error) => { - eprintln!("trustsc-medui-check: failed to load the image packages: {error}"); + report_early_failure( + &format!("failed to load the image packages: {error}"), + path, + code::UNREGISTERED, + format, + ); return ExitCode::FAILURE; } }; @@ -74,21 +130,96 @@ fn main() -> ExitCode { ImagePackages::new(&image_packages), ) { Ok(compiled) => { - println!("OK {} ({} nodes)", screen_id, compiled.nodes.len()); + match format { + Format::Text => println!("OK {} ({} nodes)", screen_id, compiled.nodes.len()), + // A clean run still emits the envelope, so a consumer parses one shape either way + // rather than having to special-case success. + Format::Json => report(&[], path, format), + } ExitCode::SUCCESS } Err(diagnostics) => { - print_diagnostics(&diagnostics); + report(&diagnostics, path, format); ExitCode::FAILURE } } } +/// Reports failures that occur before the parser or compiler can return a diagnostic. JSON mode +/// still emits the standard envelope, while text mode preserves the CLI's concise stderr form. +fn report_early_failure(message: &str, path: &str, error_code: &'static str, format: Format) { + match format { + Format::Text => eprintln!("trustsc-medui-check: {message}"), + Format::Json => report( + &[Diagnostic { + code: error_code, + file: String::new(), + message: message.to_string(), + line: None, + column: None, + severity: Severity::Error, + fix_hint: String::new(), + }], + path, + format, + ), + } +} + +fn report(diagnostics: &[Diagnostic], path: &str, format: Format) { + match format { + Format::Text => print_diagnostics(diagnostics), + Format::Json => println!("{}", envelope(diagnostics, path)), + } +} + +/// The shared envelope. Positions are emitted as `0` for "unknown" rather than as `null`, which is +/// what `schemas/diagnostic.schema.json` requires and what `spec/diagnostics.md` defines `0` to +/// mean; `file` is the path this run was given, so no finding carries the empty string the schema +/// forbids. +fn envelope(diagnostics: &[Diagnostic], path: &str) -> String { + let findings = diagnostics + .iter() + .map(|diagnostic| { + serde_json::json!({ + "file": path, + "line": diagnostic.line.unwrap_or(0), + "column": diagnostic.column.unwrap_or(0), + "code": diagnostic.code, + "severity": match diagnostic.severity { + Severity::Error => "error", + Severity::Warning => "warning", + Severity::Note => "note", + }, + "message": diagnostic.message, + "fixHint": diagnostic.fix_hint, + }) + }) + .collect::>(); + + serde_json::json!({ + "tool": "trustsc-medui-check", + "filesChecked": 1, + "findings": findings, + }) + .to_string() +} + fn print_diagnostics(diagnostics: &[Diagnostic]) { for diagnostic in diagnostics { - match diagnostic.line { - Some(line) => eprintln!("trustsc-medui-check: line {line}: {}", diagnostic.message), - None => eprintln!("trustsc-medui-check: {}", diagnostic.message), + match (diagnostic.line, diagnostic.column) { + (Some(line), Some(column)) => eprintln!( + "trustsc-medui-check: [{}] {line}:{column}: {}", + diagnostic.code, diagnostic.message + ), + (Some(line), None) => eprintln!( + "trustsc-medui-check: [{}] line {line}: {}", + diagnostic.code, diagnostic.message + ), + (None, _) => eprintln!( + "trustsc-medui-check: [{}] {}", + diagnostic.code, diagnostic.message + ), } } } diff --git a/tools/trustsc-medui-check/tests/cli.rs b/tools/trustsc-medui-check/tests/cli.rs index fdfb931..57109c4 100644 --- a/tools/trustsc-medui-check/tests/cli.rs +++ b/tools/trustsc-medui-check/tests/cli.rs @@ -19,6 +19,31 @@ fn run(path: &Path) -> Output { .expect("trustsc-medui-check should run") } +fn run_json(path: &Path) -> Output { + Command::new(env!("CARGO_BIN_EXE_trustsc-medui-check")) + .arg("--format=json") + .arg(path) + .output() + .expect("trustsc-medui-check should run") +} + +#[test] +fn json_mode_envelopes_source_read_failures() { + let missing = std::env::temp_dir().join(format!( + "trustsc-medui-check-missing-{}-{:?}.medui", + std::process::id(), + std::thread::current().id() + )); + let output = run_json(&missing); + + assert!(!output.status.success()); + assert!(output.stderr.is_empty(), "stderr was: {}", String::from_utf8_lossy(&output.stderr)); + let envelope: serde_json::Value = serde_json::from_slice(&output.stdout) + .expect("--format=json should emit an envelope for an unreadable source"); + assert_eq!(envelope["findings"][0]["code"], "MEDUI-E003"); + assert_eq!(envelope["findings"][0]["file"], missing.to_string_lossy().as_ref()); +} + #[test] fn a_valid_screen_prints_ok_and_exits_zero() { let path = repo_root().join("examples/hello_world/hello_world.medui"); @@ -102,3 +127,115 @@ impl Drop for TempMeduiFile { let _ = std::fs::remove_file(&self.path); } } + + +/// Checks `--format=json` against the finding envelope in the *pinned* contract rather than +/// against a copy of it here, so a required member added upstream fails this test instead of +/// silently making the output non-conformant. Skipped without the checkout, and a hard failure in +/// CI, for the same reason the shared conformance suite is (`MEDUI-DEC-005`). +#[test] +fn json_output_satisfies_the_pinned_diagnostic_schema() { + let Some(root) = std::env::var_os("MEDUI_CONFORMANCE_DIR") else { + assert!( + std::env::var_os("CI").is_none(), + "MEDUI_CONFORMANCE_DIR is unset in CI, so the emitted envelope is unchecked against \ + the pinned schema" + ); + eprintln!("diagnostic-schema check: SKIPPED — set MEDUI_CONFORMANCE_DIR to run it."); + return; + }; + let schema: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(PathBuf::from(&root).join("schemas/diagnostic.schema.json")) + .expect("the pinned schema should read"), + ) + .expect("the pinned schema should parse"); + + // A screen with a genuine syntax error, so there is a finding to inspect. + let original = std::fs::read_to_string(repo_root().join("examples/hello_world/hello_world.medui")) + .expect("hello_world.medui should read"); + let broken = original.replace("hello-world-label", "hello world label"); + assert_ne!( + broken, original, + "the fixture anchor `hello-world-label` is gone from hello_world.medui; pick a new one so \ + this test still produces a syntax error" + ); + let file = TempMeduiFile::new(&broken); + let output = run_json(file.path()); + assert!( + !output.status.success(), + "the broken screen should be rejected; stderr was {:?}", + String::from_utf8_lossy(&output.stderr) + ); + + let envelope: serde_json::Value = serde_json::from_str(&String::from_utf8_lossy(&output.stdout)) + .expect("--format=json should emit valid JSON"); + + assert_object_matches(&envelope, &schema, "envelope"); + + let findings = envelope["findings"] + .as_array() + .expect("findings should be an array"); + assert!(!findings.is_empty(), "the broken screen should report a finding"); + let item_schema = &schema["properties"]["findings"]["items"]; + for finding in findings { + assert_object_matches(finding, item_schema, "finding"); + + // The pattern and enum are asserted literally: if the contract changes either, this fails + // and a human decides what the new shape means rather than a loose check quietly passing. + assert_eq!( + item_schema["properties"]["code"]["pattern"], "^MEDUI-E[0-9]{3}$", + "the pinned code pattern changed; update this check deliberately" + ); + let code = finding["code"].as_str().expect("code should be a string"); + assert!( + code.len() == 10 + && code.starts_with("MEDUI-E") + && code[7..].bytes().all(|b| b.is_ascii_digit()), + "code {code:?} does not match the pinned pattern" + ); + + let severities = item_schema["properties"]["severity"]["enum"] + .as_array() + .expect("severity should declare an enum"); + assert!( + severities.contains(&finding["severity"]), + "severity {:?} is not one of {severities:?}", + finding["severity"] + ); + + for key in ["line", "column"] { + let value = finding[key].as_i64().unwrap_or_else(|| { + panic!("{key} should be an integer, got {:?}", finding[key]) + }); + assert!(value >= 0, "{key} should be non-negative, got {value}"); + } + assert!( + !finding["file"].as_str().unwrap_or_default().is_empty(), + "file must be non-empty; the schema sets minLength 1" + ); + } +} + +/// Asserts every member the schema requires is present, and that nothing undeclared is emitted — +/// both schemas set `additionalProperties: false`. +fn assert_object_matches(value: &serde_json::Value, schema: &serde_json::Value, what: &str) { + let object = value + .as_object() + .unwrap_or_else(|| panic!("{what} should be an object, got {value:?}")); + for required in schema["required"] + .as_array() + .expect("the schema should list required members") + { + let key = required.as_str().expect("a required member names a string"); + assert!(object.contains_key(key), "{what} is missing required member {key:?}"); + } + let declared = schema["properties"] + .as_object() + .expect("the schema should declare properties"); + for key in object.keys() { + assert!( + declared.contains_key(key), + "{what} emits {key:?}, which the schema does not declare (additionalProperties: false)" + ); + } +} diff --git a/tools/trustsc-medui-studio/frontend/dist/app.js b/tools/trustsc-medui-studio/frontend/dist/app.js index 19a1ee3..e5226e9 100644 --- a/tools/trustsc-medui-studio/frontend/dist/app.js +++ b/tools/trustsc-medui-studio/frontend/dist/app.js @@ -70,10 +70,21 @@ function renderDiagnostics(container, diagnostics) { return; } const items = diagnostics.map((diagnostic) => { - const location = diagnostic.line !== null ? `line ${diagnostic.line}: ` : ""; - return el("li", {}, [`${location}${diagnostic.message}`]); + const position = diagnostic.line === null + ? "" + : `line ${diagnostic.line}${diagnostic.column === null ? "" : `, column ${diagnostic.column}`}`; + const source = [diagnostic.file, position].filter(Boolean).join(": "); + const identity = diagnostic.code ? `[${diagnostic.code}]` : ""; + const prefix = [identity, source].filter(Boolean).join(" "); + const hint = diagnostic.fix_hint ? ` Fix: ${diagnostic.fix_hint}` : ""; + return el("li", {}, [`${prefix ? `${prefix}: ` : ""}${diagnostic.message}${hint}`]); }); - container.className = "diagnostics diagnostics--error"; + const severity = diagnostics.some((diagnostic) => diagnostic.severity === "Error") + ? "error" + : diagnostics.some((diagnostic) => diagnostic.severity === "Warning") + ? "warning" + : "note"; + container.className = `diagnostics diagnostics--${severity}`; container.replaceChildren(el("strong", {}, [`${diagnostics.length} diagnostic(s)`]), el("ul", {}, items)); } function applyZoomStyle(stage, surfaceWidth) { @@ -255,7 +266,15 @@ async function renderScreenView(screenId, requestedLocale) { inspector?.showRow(rowId); }, onCompileError: (message) => { - renderDiagnostics(diagnosticsContainer, [{ message, line: null, severity: "Error" }]); + renderDiagnostics(diagnosticsContainer, [{ + code: "MEDUI-E010", + file: "", + message, + line: null, + column: null, + severity: "Error", + fix_hint: "", + }]); proposeButton.disabled = true; }, onDocumentChanged: (diff) => renderChanges(safetyBanner, changesDrawer, changesList, changesSummary, proposeButton, diff), diff --git a/tools/trustsc-medui-studio/frontend/dist/styles.css b/tools/trustsc-medui-studio/frontend/dist/styles.css index ece787b..d487bfa 100644 --- a/tools/trustsc-medui-studio/frontend/dist/styles.css +++ b/tools/trustsc-medui-studio/frontend/dist/styles.css @@ -5,6 +5,10 @@ --golden: #d4a72b; --error-bg: #fdecea; --error-fg: #7a1f14; + --warning-bg: #fff4d6; + --warning-fg: #6b4b00; + --note-bg: #eaf2ff; + --note-fg: #244a7c; } * { @@ -193,6 +197,16 @@ h1 { color: var(--error-fg); } +.diagnostics--warning { + background: var(--warning-bg); + color: var(--warning-fg); +} + +.diagnostics--note { + background: var(--note-bg); + color: var(--note-fg); +} + .diagnostics ul { margin: 0.4rem 0 0; padding-left: 1.2rem; diff --git a/tools/trustsc-medui-studio/frontend/src/api.ts b/tools/trustsc-medui-studio/frontend/src/api.ts index c048216..51d59c0 100644 --- a/tools/trustsc-medui-studio/frontend/src/api.ts +++ b/tools/trustsc-medui-studio/frontend/src/api.ts @@ -51,12 +51,16 @@ export interface CompiledNodeSummary { golden_checks: CvCheckKind[]; } -export type Severity = "Error"; +export type Severity = "Error" | "Warning" | "Note"; export interface Diagnostic { + code: string; + file: string; message: string; line: number | null; + column: number | null; severity: Severity; + fix_hint: string; } export interface CompiledSummary { diff --git a/tools/trustsc-medui-studio/frontend/src/app.ts b/tools/trustsc-medui-studio/frontend/src/app.ts index 79614f9..345a77a 100644 --- a/tools/trustsc-medui-studio/frontend/src/app.ts +++ b/tools/trustsc-medui-studio/frontend/src/app.ts @@ -102,10 +102,21 @@ function renderDiagnostics(container: HTMLElement, diagnostics: Diagnostic[]): v return; } const items = diagnostics.map((diagnostic) => { - const location = diagnostic.line !== null ? `line ${diagnostic.line}: ` : ""; - return el("li", {}, [`${location}${diagnostic.message}`]); + const position = diagnostic.line === null + ? "" + : `line ${diagnostic.line}${diagnostic.column === null ? "" : `, column ${diagnostic.column}`}`; + const source = [diagnostic.file, position].filter(Boolean).join(": "); + const identity = diagnostic.code ? `[${diagnostic.code}]` : ""; + const prefix = [identity, source].filter(Boolean).join(" "); + const hint = diagnostic.fix_hint ? ` Fix: ${diagnostic.fix_hint}` : ""; + return el("li", {}, [`${prefix ? `${prefix}: ` : ""}${diagnostic.message}${hint}`]); }); - container.className = "diagnostics diagnostics--error"; + const severity = diagnostics.some((diagnostic) => diagnostic.severity === "Error") + ? "error" + : diagnostics.some((diagnostic) => diagnostic.severity === "Warning") + ? "warning" + : "note"; + container.className = `diagnostics diagnostics--${severity}`; container.replaceChildren(el("strong", {}, [`${diagnostics.length} diagnostic(s)`]), el("ul", {}, items)); } @@ -311,7 +322,15 @@ async function renderScreenView(screenId: string, requestedLocale: string | null inspector?.showRow(rowId); }, onCompileError: (message) => { - renderDiagnostics(diagnosticsContainer, [{ message, line: null, severity: "Error" }]); + renderDiagnostics(diagnosticsContainer, [{ + code: "MEDUI-E010", + file: "", + message, + line: null, + column: null, + severity: "Error", + fix_hint: "", + }]); proposeButton.disabled = true; }, onDocumentChanged: (diff) => renderChanges(safetyBanner, changesDrawer, changesList, changesSummary, proposeButton, diff), diff --git a/tools/trustsc-medui-studio/frontend/src/styles.css b/tools/trustsc-medui-studio/frontend/src/styles.css index ece787b..d487bfa 100644 --- a/tools/trustsc-medui-studio/frontend/src/styles.css +++ b/tools/trustsc-medui-studio/frontend/src/styles.css @@ -5,6 +5,10 @@ --golden: #d4a72b; --error-bg: #fdecea; --error-fg: #7a1f14; + --warning-bg: #fff4d6; + --warning-fg: #6b4b00; + --note-bg: #eaf2ff; + --note-fg: #244a7c; } * { @@ -193,6 +197,16 @@ h1 { color: var(--error-fg); } +.diagnostics--warning { + background: var(--warning-bg); + color: var(--warning-fg); +} + +.diagnostics--note { + background: var(--note-bg); + color: var(--note-fg); +} + .diagnostics ul { margin: 0.4rem 0 0; padding-left: 1.2rem; diff --git a/tools/trustsc-medui-studio/src/dto.rs b/tools/trustsc-medui-studio/src/dto.rs index e44cc0e..390b85a 100644 --- a/tools/trustsc-medui-studio/src/dto.rs +++ b/tools/trustsc-medui-studio/src/dto.rs @@ -4,13 +4,13 @@ //! its governed-crate counterpart lives here, never there. use serde::{Deserialize, Serialize}; +use trustsc::{ClockFormat, CvCheckKind, LayoutKind, SystemEvent}; use trustsc_ui_dsl_authoring::{ CompiledNodeSpec, CompiledScreenSpec, Diagnostic, Dimension, GoldenReferenceSpec, ImageInfo, LayoutDefinition, LocaleEntry, NodeDefinition, NodeKind, NumericTemplateInfo, PropDomain, - PropSchema, RowDefinition, SafetyCriticalDefinition, ScreenDefinition, ScreenItem, - Severity, TextKeyInfo, WidgetSchema, + PropSchema, RowDefinition, SafetyCriticalDefinition, ScreenDefinition, ScreenItem, Severity, + TextKeyInfo, WidgetSchema, }; -use trustsc::{ClockFormat, CvCheckKind, LayoutKind, SystemEvent}; // --------------------------------------------------------------------------------------------- // Small closed-set enums: trustsc_ui's own types can't derive serde (no serde in crates/), so @@ -179,7 +179,11 @@ pub struct SafetyCriticalDto { impl From for SafetyCriticalDto { fn from(value: SafetyCriticalDefinition) -> Self { SafetyCriticalDto { - cv_checks: value.cv_checks.into_iter().map(CvCheckKindDto::from).collect(), + cv_checks: value + .cv_checks + .into_iter() + .map(CvCheckKindDto::from) + .collect(), } } } @@ -269,13 +273,23 @@ impl From for NodeKindDto { NodeKind::VulkanViewport { stream_source } => { NodeKindDto::VulkanViewport { stream_source } } - NodeKind::SignalTrace { stream_source, color_token } => { - NodeKindDto::SignalTrace { stream_source, color_token } - } - NodeKind::Label { text_key, color_token } => { - NodeKindDto::Label { text_key, color_token } - } - NodeKind::Clock { format } => NodeKindDto::Clock { format: format.into() }, + NodeKind::SignalTrace { + stream_source, + color_token, + } => NodeKindDto::SignalTrace { + stream_source, + color_token, + }, + NodeKind::Label { + text_key, + color_token, + } => NodeKindDto::Label { + text_key, + color_token, + }, + NodeKind::Clock { format } => NodeKindDto::Clock { + format: format.into(), + }, NodeKind::NumericDisplay { requirement_id, template_id, @@ -345,13 +359,23 @@ impl From for NodeKind { NodeKindDto::VulkanViewport { stream_source } => { NodeKind::VulkanViewport { stream_source } } - NodeKindDto::SignalTrace { stream_source, color_token } => { - NodeKind::SignalTrace { stream_source, color_token } - } - NodeKindDto::Label { text_key, color_token } => { - NodeKind::Label { text_key, color_token } - } - NodeKindDto::Clock { format } => NodeKind::Clock { format: format.into() }, + NodeKindDto::SignalTrace { + stream_source, + color_token, + } => NodeKind::SignalTrace { + stream_source, + color_token, + }, + NodeKindDto::Label { + text_key, + color_token, + } => NodeKind::Label { + text_key, + color_token, + }, + NodeKindDto::Clock { format } => NodeKind::Clock { + format: format.into(), + }, NodeKindDto::NumericDisplay { requirement_id, template_id, @@ -463,7 +487,11 @@ impl From for RowDefinitionDto { height: value.height.into(), spacing: value.spacing, background: value.background, - children: value.children.into_iter().map(NodeDefinitionDto::from).collect(), + children: value + .children + .into_iter() + .map(NodeDefinitionDto::from) + .collect(), } } } @@ -475,7 +503,11 @@ impl From for RowDefinition { height: value.height.into(), spacing: value.spacing, background: value.background, - children: value.children.into_iter().map(NodeDefinition::from).collect(), + children: value + .children + .into_iter() + .map(NodeDefinition::from) + .collect(), } } } @@ -555,29 +587,41 @@ pub fn contains_panel(screen: &ScreenDefinitionDto) -> bool { #[derive(Clone, Copy, Debug, Serialize)] pub enum SeverityDto { Error, + Warning, + Note, } impl From for SeverityDto { fn from(value: Severity) -> Self { match value { Severity::Error => SeverityDto::Error, + Severity::Warning => SeverityDto::Warning, + Severity::Note => SeverityDto::Note, } } } #[derive(Clone, Debug, Serialize)] pub struct DiagnosticDto { + pub code: String, + pub file: String, pub message: String, pub line: Option, + pub column: Option, pub severity: SeverityDto, + pub fix_hint: String, } impl From for DiagnosticDto { fn from(value: Diagnostic) -> Self { DiagnosticDto { + code: value.code.to_string(), + file: value.file, message: value.message, line: value.line, + column: value.column, severity: value.severity.into(), + fix_hint: value.fix_hint, } } } @@ -612,11 +656,21 @@ pub struct CompiledNodeSummaryDto { pub golden_checks: Vec, } -fn compiled_node_to_dto(node: CompiledNodeSpec, golden: &[GoldenReferenceSpec]) -> CompiledNodeSummaryDto { +fn compiled_node_to_dto( + node: CompiledNodeSpec, + golden: &[GoldenReferenceSpec], +) -> CompiledNodeSummaryDto { let golden_checks = golden .iter() .find(|entry| entry.node_id == node.id) - .map(|entry| entry.cv_checks.iter().copied().map(CvCheckKindDto::from).collect()) + .map(|entry| { + entry + .cv_checks + .iter() + .copied() + .map(CvCheckKindDto::from) + .collect() + }) .unwrap_or_default(); CompiledNodeSummaryDto { id: node.id.clone(), @@ -768,7 +822,11 @@ impl From for TextKeyInfoDto { fn from(value: TextKeyInfo) -> Self { TextKeyInfoDto { string_id: value.string_id, - entries: value.entries.into_iter().map(LocaleEntryDto::from).collect(), + entries: value + .entries + .into_iter() + .map(LocaleEntryDto::from) + .collect(), } } }