From 62238a6b29f71b06f2503a31da028d74944af548 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Thu, 13 Aug 2026 22:24:41 +0200 Subject: [PATCH 1/7] Adopt shared MedUI contract --- .claude/skills/medui-authoring/SKILL.md | 5 +- .github/workflows/ci.yml | 9 ++ .../src/diagnostic.rs | 44 ++++++++ .../tests/shared_conformance.rs | 27 +++++ ...DR-008-deterministic-medui-dsl-boundary.md | 7 ++ ...dui-compilation-and-generated-artifacts.md | 7 ++ ...ty-monitor-and-vulkan-viewport-contract.md | 4 + docs/dsl/overview.md | 5 + medui-conformance.toml | 6 + tools/trustsc-medui-check/src/main.rs | 19 +++- tools/trustsc-medui-studio/src/dto.rs | 104 ++++++++++++++---- 11 files changed, 209 insertions(+), 28 deletions(-) create mode 100644 crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs create mode 100644 medui-conformance.toml 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..68b231c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,13 @@ jobs: - name: Check out repository uses: actions/checkout@v4 + - name: Check out pinned MedUI conformance contract + uses: actions/checkout@v4 + with: + repository: Compliatory/MedUI + ref: 763499016fdf16e9ba697cc938647ea67e8f8145 + path: .medui-conformance + - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable @@ -34,6 +41,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/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs index 81a373b..567cc9f 100644 --- a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs +++ b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs @@ -6,13 +6,22 @@ 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, + /// Repository-relative source file when the caller knows it; 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 { @@ -25,13 +34,48 @@ impl Diagnostic { let message = error.to_string(); let line = extract_line_number(&message); Diagnostic { + code: classify(&message), + file: String::new(), message, line, + column: None, severity: Severity::Error, + fix_hint: String::new(), } } } +/// Transitional classification for the line-oriented parser. Codes are canonical now; replacing +/// message-based classification with positioned lexer errors is tracked by the shared syntax +/// conformance migration and does not change this public envelope. +fn classify(message: &str) -> &'static str { + if message.contains("nested Row") { + "MEDUI-E015" + } else if message.contains("unsupported component") { + "MEDUI-E011" + } else if message.contains("unsupported property") + || message.contains("unsupported Row property") + { + "MEDUI-E013" + } else if message.contains("must declare") { + "MEDUI-E012" + } else if message.contains("unknown color") || message.contains("unknown theme") { + "MEDUI-E030" + } else if message.contains("unknown text") || message.contains("unknown string") { + "MEDUI-E031" + } else if message.contains("widest") || message.contains("budget") || message.contains("fit") { + "MEDUI-E050" + } else if message.contains("outside") || message.contains("exceeds the available surface") { + "MEDUI-E052" + } else if message.contains("safety-critical") && message.contains("requirement") { + "MEDUI-E070" + } else if message.contains("CV check") { + "MEDUI-E071" + } else { + "MEDUI-E010" + } +} + fn extract_line_number(message: &str) -> Option { let mut search = message; let mut found = None; 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..a8f0229 --- /dev/null +++ b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs @@ -0,0 +1,27 @@ +//! Candidate shared-contract checks. CI supplies the exact pinned checkout through +//! `MEDUI_CONFORMANCE_DIR`; local test runs skip these cases when it is absent. + +use std::{fs, path::Path}; + +use trustsc_ui_dsl_authoring::parse_medui_source; + +fn source(root: &Path, relative: &str) -> String { + fs::read_to_string(root.join(relative)).expect("shared conformance source should read") +} + +#[test] +fn pinned_shared_syntax_cases() { + let Some(root) = std::env::var_os("MEDUI_CONFORMANCE_DIR") else { + return; + }; + let root = Path::new(&root); + + let accepted = source(root, "conformance/syntax/accepted-comments/source.medui"); + parse_medui_source(&accepted).expect("shared comments case should parse"); + + let nested = source(root, "conformance/syntax/rejected-nested-row/source.medui"); + let diagnostics = parse_medui_source(&nested).expect_err("nested Row should be rejected"); + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].code, "MEDUI-E015"); + assert_eq!(diagnostics[0].line, Some(6)); +} diff --git a/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md b/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md index a6783c4..dd955e6 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/763499016fdf16e9ba697cc938647ea67e8f8145/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..7fdf7f4 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/763499016fdf16e9ba697cc938647ea67e8f8145/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..a537372 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/763499016fdf16e9ba697cc938647ea67e8f8145/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/medui-conformance.toml b/medui-conformance.toml new file mode 100644 index 0000000..119c90e --- /dev/null +++ b/medui-conformance.toml @@ -0,0 +1,6 @@ +repository = "https://github.com/Compliatory/MedUI" +version = "0.1.0-candidate" +commit = "763499016fdf16e9ba697cc938647ea67e8f8145" +# 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"] diff --git a/tools/trustsc-medui-check/src/main.rs b/tools/trustsc-medui-check/src/main.rs index cd9aacf..fb43c06 100644 --- a/tools/trustsc-medui-check/src/main.rs +++ b/tools/trustsc-medui-check/src/main.rs @@ -7,7 +7,8 @@ use std::process::ExitCode; use trustsc_ui_dsl_authoring::{ - CompileOptions, Diagnostic, ImagePackages, TextPackages, compile_screen_definition, parse_medui_source, + CompileOptions, Diagnostic, ImagePackages, TextPackages, compile_screen_definition, + parse_medui_source, }; /// Matches the fallback every other tool in this repo uses for a screen with no `surface:` pin @@ -86,9 +87,19 @@ fn main() -> ExitCode { 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-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(), } } } From 869cfe50d625cbff22608ee5e918612d9ff01058 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sat, 15 Aug 2026 07:44:07 +0200 Subject: [PATCH 2/7] Drive shared conformance from the pinned cases The shared conformance test copied its expectations into Rust instead of reading the pinned checkout, and returned early whenever MEDUI_CONFORMANCE_DIR was unset. Both defeat the point: MedUI could change an expected code or position without TrustSC noticing, and dropping the env var from CI would have left the suite green while asserting nothing -- exactly the silent skip of a claimed phase that MEDUI-DEC-005 forbids. - Every expectation now comes from the pinned case.json. The harness walks conformance/**/case.json, checks each declared phase against its directory, and asserts code, line and column against that data. - A missing checkout under CI is a hard failure; locally it prints an explicit skip notice. - A claimed capability must name a phase the harness can observe and must be backed by a case that actually ran. Claiming semantics, layout or safety fails with a pointer to the missing compile_medui_source adapter rather than running those cases through the parser. - medui-conformance.toml is now the single source of the pin; CI derives its checkout ref from it, so the workflow and the manifest cannot drift. parse_screen is line-oriented and trims each line, so no column reaches Diagnostic::column while every shared case pins one. The new positions key records that deviation instead of dropping the assertion: "line-only" requires each diagnostic to carry no column at all, so a positioned lexer fails the suite until positions is set to "full" and the pinned columns are genuinely checked. Whether an implementation reporting an unknown position satisfies a case pinning a known one is undefined in the shared contract and needs a MEDUI-DEC-005 clarification. crates/ takes no third-party dependencies, so the manifest and the JSON subset the cases use are read directly. Both readers are strict -- escapes, floats, null, duplicate keys and unknown manifest keys all fail loudly -- so nothing can be misread into a vacuous pass. --- .github/workflows/ci.yml | 13 +- .../tests/shared_conformance.rs | 626 +++++++++++++++++- medui-conformance.toml | 9 + 3 files changed, 630 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 68b231c..7863cca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,11 +19,22 @@ 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/^commit = "\([0-9a-f]\{40\}\)"$/\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: 763499016fdf16e9ba697cc938647ea67e8f8145 + ref: ${{ steps.medui-contract.outputs.commit }} path: .medui-conformance - name: Install Rust toolchain diff --git a/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs index a8f0229..7391ca4 100644 --- a/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs +++ b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs @@ -1,27 +1,619 @@ -//! Candidate shared-contract checks. CI supplies the exact pinned checkout through -//! `MEDUI_CONFORMANCE_DIR`; local test runs skip these cases when it is absent. +//! 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. +//! +//! 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::{fs, path::Path}; +use std::{ + collections::BTreeSet, + fs, + path::{Path, PathBuf}, +}; -use trustsc_ui_dsl_authoring::parse_medui_source; +use trustsc_ui_dsl_authoring::{Diagnostic, parse_medui_source}; -fn source(root: &Path, relative: &str) -> String { - fs::read_to_string(root.join(relative)).expect("shared conformance source should read") -} +/// 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_syntax_cases() { - let Some(root) = std::env::var_os("MEDUI_CONFORMANCE_DIR") else { +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; }; - let root = Path::new(&root); - let accepted = source(root, "conformance/syntax/accepted-comments/source.medui"); - parse_medui_source(&accepted).expect("shared comments case should parse"); + 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 are 1-based and `0` means unknown. + assert_eq!( + i64::from(actual.line.unwrap_or(0)), + expected.line, + "{}: diagnostic line", + case.id + ); + + match manifest.positions { + Positions::Full => assert_eq!( + i64::from(actual.column.unwrap_or(0)), + expected.column, + "{}: diagnostic column", + case.id + ), + // Not "columns are unchecked" but "columns are known-absent": the moment the parser + // starts reporting one, this fails and forces `positions = "full"` and a real check. + Positions::LineOnly => assert!( + actual.column.is_none(), + "{}: medui-conformance.toml declares positions = \"line-only\", but the parser \ + reported column {:?}. Set positions = \"full\" so the pinned column {} is \ + actually checked.", + case.id, + actual.column, + 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 + } + } +} + +// ------------------------------------------------------------------------------------------- +// medui-conformance.toml +// ------------------------------------------------------------------------------------------- + +#[derive(Debug, Clone, Copy, Eq, PartialEq)] +enum Positions { + /// Diagnostics carry exact 1-based UTF-8 byte columns; pinned columns are checked. + Full, + /// Diagnostics carry no column at all; see the key's comment in `medui-conformance.toml`. + LineOnly, +} + +#[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, + other => panic!( + "{}:{}: positions must be \"full\" or \"line-only\", 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()) + } +} - let nested = source(root, "conformance/syntax/rejected-nested-row/source.medui"); - let diagnostics = parse_medui_source(&nested).expect_err("nested Row should be rejected"); - assert_eq!(diagnostics.len(), 1); - assert_eq!(diagnostics[0].code, "MEDUI-E015"); - assert_eq!(diagnostics[0].line, Some(6)); +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/medui-conformance.toml b/medui-conformance.toml index 119c90e..52c996a 100644 --- a/medui-conformance.toml +++ b/medui-conformance.toml @@ -1,6 +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 = "763499016fdf16e9ba697cc938647ea67e8f8145" # 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"] +# How precisely this implementation can locate a diagnostic. `parse_screen` is line-oriented and +# trims each line before matching, so no column survives to `Diagnostic::column`; the shared cases +# nonetheless pin one. `line-only` records that deviation explicitly instead of dropping the +# assertion: the harness then *requires* every diagnostic to carry no column, so the day a +# positioned lexer lands the suite fails until this is set to `full` and the columns are checked. +positions = "line-only" From 9f502129a6ab328d176183a24b3873c64f5ade7f Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sat, 15 Aug 2026 07:55:10 +0200 Subject: [PATCH 3/7] Assign diagnostic codes where errors are raised classify() recovered a MEDUI-E### identity by substring-matching the error's Display output, but spec/diagnostics.md says a message "may be reworded" while a code's meaning is stable -- so a stable identity depended on prose. Rewording any format! string silently reclassified its diagnostic, and nothing tested the mapping. Each of the 116 raise sites in trustsc-ui-dsl-authoring now names its own code, carried on the error itself. ValidationError gains an optional opaque code and the crate that raises the error assigns it; trustsc-core still owns no registry. Removing the message matching fixes what it got wrong: - duplicate node id reported E010 rather than E014, inside the syntax phase medui-conformance.toml claims. - E031 (unknown text key) and E070 were unreachable: no message contained the substrings their branches looked for. E031 now has its raise site; E070 stays unemitted because the requirement rule is enforced per component schema, not by @safety_critical, so the shared safety case would still not pass and safety remains unclaimed. - Missing text keys, locale gaps and text budget overruns all collapsed into E010; they now report E031, E032 and E050. - "exceeds available surface" missed the branch testing for "exceeds the available surface" and fell through to E010; surface and overflow conditions now report E052 and E051. - unsupported charset, clock format, layout and system event, and unknown image packages and templates, reported E010 by accident. They report it deliberately through code::UNREGISTERED, which marks the 24 conditions the pinned registry has no code for so they stay greppable and can be raised upstream. compile_medui_source_to_rust flattened every failure into one untagged error; a single diagnostic now keeps its identity, which is how the duplicate-node-id test caught it. Three tests guard the result: a table pinning parse-time sources to codes, a compile-time pair covering E014 and E030, and a scan asserting no untagged raise site remains. --- crates/trustsc-core/src/lib.rs | 19 + .../src/diagnostic.rs | 105 +++-- crates/trustsc-ui-dsl-authoring/src/lib.rs | 394 ++++++++++++------ 3 files changed, 356 insertions(+), 162 deletions(-) diff --git a/crates/trustsc-core/src/lib.rs b/crates/trustsc-core/src/lib.rs index 90c7dff..7817414 100644 --- a/crates/trustsc-core/src/lib.rs +++ b/crates/trustsc-core/src/lib.rs @@ -7,14 +7,33 @@ pub type TrustScResult = Result; #[derive(Clone, Debug, Eq, PartialEq)] pub struct ValidationError { message: String, + code: Option<&'static str>, } impl ValidationError { pub fn new(message: impl Into) -> Self { Self { message: message.into(), + code: 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), + } + } + + /// The stable identity assigned at the point the error was raised, when there is one. + pub fn code(&self) -> Option<&'static str> { + self.code + } } impl Display for ValidationError { diff --git a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs index 567cc9f..354765f 100644 --- a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs +++ b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs @@ -25,16 +25,26 @@ pub struct Diagnostic { } 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. + /// + /// The line number is still recovered from the message: every parser error embeds it as + /// `line {N}` somewhere in the text (not always at the end — e.g. + /// `"component at line {n} must declare \`id\`"`). That stays message-coupled until the + /// line-oriented parser is replaced by a positioned lexer, which is also what would supply + /// the column the shared cases pin. pub fn from_validation_error(error: &ValidationError) -> Diagnostic { let message = error.to_string(); let line = extract_line_number(&message); Diagnostic { - code: classify(&message), + // 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, @@ -45,35 +55,60 @@ impl Diagnostic { } } -/// Transitional classification for the line-oriented parser. Codes are canonical now; replacing -/// message-based classification with positioned lexer errors is tracked by the shared syntax -/// conformance migration and does not change this public envelope. -fn classify(message: &str) -> &'static str { - if message.contains("nested Row") { - "MEDUI-E015" - } else if message.contains("unsupported component") { - "MEDUI-E011" - } else if message.contains("unsupported property") - || message.contains("unsupported Row property") - { - "MEDUI-E013" - } else if message.contains("must declare") { - "MEDUI-E012" - } else if message.contains("unknown color") || message.contains("unknown theme") { - "MEDUI-E030" - } else if message.contains("unknown text") || message.contains("unknown string") { - "MEDUI-E031" - } else if message.contains("widest") || message.contains("budget") || message.contains("fit") { - "MEDUI-E050" - } else if message.contains("outside") || message.contains("exceeds the available surface") { - "MEDUI-E052" - } else if message.contains("safety-critical") && message.contains("requirement") { - "MEDUI-E070" - } else if message.contains("CV check") { - "MEDUI-E071" - } else { - "MEDUI-E010" - } +/// 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) } fn extract_line_number(message: &str) -> Option { diff --git a/crates/trustsc-ui-dsl-authoring/src/lib.rs b/crates/trustsc-ui-dsl-authoring/src/lib.rs index 44b1628..30bb227 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; 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,24 @@ 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()), + 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 +247,8 @@ fn parse_screen(source: &str) -> TrustScResult { .collect::>(); if lines.len() < 3 { - return Err(ValidationError::new( + return Err(coded( + code::UNEXPECTED_TOKEN, "MedUI source must contain a screen header, layout, and closing brace", )); } @@ -267,7 +278,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(code::UNEXPECTED_TOKEN, format!( "unexpected content after screen closing brace at line {line_number}" ))); } @@ -282,7 +293,7 @@ fn parse_screen(source: &str) -> TrustScResult { if line == "Row {" { if pending_safety.is_some() { - return Err(ValidationError::new(format!( + return Err(coded(code::FORBIDDEN_CONSTRUCT, format!( "@safety_critical cannot annotate a Row container at line {line_number}" ))); } @@ -316,7 +327,8 @@ fn parse_screen(source: &str) -> TrustScResult { } if items.is_empty() { - return Err(ValidationError::new( + return Err(coded( + code::MISSING_FIELD, "MedUI screen must declare at least one component", )); } @@ -359,7 +371,7 @@ fn parse_row( } if line == "Row {" { - return Err(ValidationError::new(format!( + return Err(coded(code::NESTED_ROW, format!( "nested Row containers are not supported at line {line_number}" ))); } @@ -399,7 +411,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(code::UNEXPECTED_TOKEN, format!( "invalid Row property `{property_line}` at line {line_number}" )) })?; @@ -413,7 +425,7 @@ fn parse_row( background = Some(parse_non_empty(*line_number, "background", value.trim())?) } other => { - return Err(ValidationError::new(format!( + return Err(coded(code::UNKNOWN_FIELD, format!( "unsupported Row property `{other}` at line {line_number}" ))); } @@ -422,19 +434,19 @@ fn parse_row( } if !closed { - return Err(ValidationError::new(format!( + return Err(coded(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(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(code::MISSING_FIELD, format!("Row {id} must declare `height`")) })?; if children.is_empty() { - return Err(ValidationError::new(format!( + return Err(coded(code::MISSING_FIELD, format!( "Row {id} must contain at least one component" ))); } @@ -457,7 +469,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(code::UNEXPECTED_TOKEN, format!( "expected `Screen {{` at line {line_number}" )) })?; @@ -468,9 +480,14 @@ fn parse_layout(line_number: usize, line: &str) -> TrustScResult TrustScResult LayoutKind::Vertical, "Horizontal" => LayoutKind::Horizontal, other => { - return Err(ValidationError::new(format!( + return Err(coded(code::UNREGISTERED, format!( "unsupported layout `{other}` at line {line_number}" ))) } @@ -500,13 +517,16 @@ 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(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( + code::UNEXPECTED_TOKEN, + format!("invalid layout property `{entry}` at line {line_number}"), + ) })?; parse_px_allowing_zero(line_number, key, value.trim()) }) @@ -518,7 +538,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(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(code::MISSING_FIELD, format!( "safety-critical annotation at line {line_number} must declare at least one CV check" ))); } @@ -561,7 +581,12 @@ fn parse_component_start(line_number: usize, line: &str) -> TrustScResult Ok(ComponentKind::CriticalButton), "VulkanViewport" => Ok(ComponentKind::VulkanViewport), @@ -573,7 +598,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(code::UNKNOWN_COMPONENT, format!( "unsupported component `{other}` at line {line_number}" ))), } @@ -606,7 +631,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(code::UNEXPECTED_TOKEN, format!( "invalid property `{property_line}` at line {property_line_number}" )) })?; @@ -647,7 +672,7 @@ fn parse_component_properties( } "charset" => charset = Some(parse_charset(*property_line_number, value)?), other => { - return Err(ValidationError::new(format!( + return Err(coded(code::UNKNOWN_FIELD, format!( "unsupported property `{other}` at line {property_line_number}" ))) } @@ -655,17 +680,17 @@ fn parse_component_properties( } let id = id.ok_or_else(|| { - ValidationError::new(format!("component at line {line_number} must declare `id`")) + coded(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(code::MISSING_FIELD, format!("component {id} must declare `width`")) })?; let height = height.ok_or_else(|| { - ValidationError::new(format!("component {id} must declare `height`")) + coded(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(code::LAYOUT_OVERFLOW, format!( "component {id}: `position` requires fixed `width`/`height` — Fill is flow-only" ))); } @@ -673,77 +698,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(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(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(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(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(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(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(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(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(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(code::MISSING_FIELD, format!("Clock {id} must declare `format`")) })?, }, ComponentKind::NumericDisplay => NodeKind::NumericDisplay { requirement_id: requirement_id.ok_or_else(|| { - ValidationError::new(format!( + coded(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(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(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(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(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(code::UNREGISTERED, format!( "StatusIndicator {id} declares {} states but {} colors", state_text_keys.len(), color_tokens.len() @@ -751,13 +776,13 @@ fn parse_component_properties( } NodeKind::StatusIndicator { requirement_id: requirement_id.ok_or_else(|| { - ValidationError::new(format!( + coded(code::MISSING_FIELD, format!( "StatusIndicator {id} must declare `requirement`" )) })?, source: { let (source_line, raw) = source.ok_or_else(|| { - ValidationError::new(format!( + coded(code::MISSING_FIELD, format!( "StatusIndicator {id} must declare `source`" )) })?; @@ -770,27 +795,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(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(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(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(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(code::MISSING_FIELD, format!("Button {id} must declare `source`")) })?; parse_quoted(source_line, "source", &raw)? }, @@ -799,25 +824,25 @@ fn parse_component_properties( } ComponentKind::TextInput => { if on_press.is_some() { - return Err(ValidationError::new(format!( + return Err(coded(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(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(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(code::MISSING_FIELD, format!("TextInput {id} must declare `color`")) })?, requirement_id, } @@ -837,7 +862,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(code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -845,7 +870,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(code::UNEXPECTED_TOKEN, format!( "{field_name} contains unsupported characters at line {line_number}" ))); } @@ -855,7 +880,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(code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -865,13 +890,13 @@ 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!( + return Err(coded(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(code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -884,7 +909,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(code::UNEXPECTED_TOKEN, format!( "text references must use t(\"key\") at line {line_number}" )) })?; @@ -895,7 +920,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(code::UNREGISTERED, format!( "unsupported system event `{other}` at line {line_number}" ))), } @@ -905,7 +930,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(code::UNREGISTERED, format!( "unsupported clock format `{other}` at line {line_number}" ))), } @@ -914,12 +939,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(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(code::UNEXPECTED_TOKEN, format!( "max_length must be greater than zero at line {line_number}" ))); } @@ -931,7 +956,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(code::UNREGISTERED, format!( "unsupported charset `{other}` at line {line_number}; approved charsets are: AsciiText" ))), } @@ -945,7 +970,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(code::UNEXPECTED_TOKEN, format!( "{field_name} must be a [..] list at line {line_number}" )) })?; @@ -956,7 +981,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(code::MISSING_FIELD, format!( "{field_name} must declare at least one entry at line {line_number}" ))); } @@ -984,7 +1009,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(code::UNEXPECTED_TOKEN, format!( "Image source must use `img(\"IMAGE-ID\")` at line {line_number}" )) })?; @@ -1001,7 +1026,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(code::UNEXPECTED_TOKEN, format!( "{field_name} must be greater than zero at line {line_number}" ))); } @@ -1014,13 +1039,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(code::UNEXPECTED_TOKEN, format!( "{field_name} must use a px unit at line {line_number}" )) })? .parse::() .map_err(|_| { - ValidationError::new(format!( + coded(code::UNEXPECTED_TOKEN, format!( "{field_name} must be a non-negative integer px value at line {line_number}" )) }) @@ -1029,7 +1054,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(code::UNEXPECTED_TOKEN, format!( "position must be `px, px` at line {line_number}" )) })?; @@ -1041,7 +1066,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(code::UNEXPECTED_TOKEN, format!( "surface must be `px, px` at line {line_number}" )) })?; @@ -1057,14 +1082,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 +1100,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 +1251,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 +1268,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 +1308,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 +1337,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 +1362,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 +1388,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 +1397,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 +1412,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 +1421,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 +1534,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 +1621,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 +1648,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 +1658,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 +1691,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 +1709,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 +1733,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 +1744,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 +1754,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 +1763,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 +1781,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 +1789,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 +1801,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 +1815,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 +1826,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 +1852,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 +1861,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 +1909,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 +3445,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 From 38dd43d6025b9affcf8a0a621b2691b7baef9567 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sat, 15 Aug 2026 17:46:38 +0200 Subject: [PATCH 4/7] Emit the shared finding envelope, and re-pin to the position rule Re-pins to Compliatory/MedUI f22f604, which defines what a case's pinned position means for an implementation that cannot report one. `positions` is no longer a TrustSC-local workaround pending an answer: the contract now specifies the key, so the harness implements a contract rule and supports all three declared precisions. A phase claimed at reduced precision is still claimed, which is what lets `syntax` stand here. trustsc-medui-check gains `--format=json`, emitting the envelope from schemas/diagnostic.schema.json: `file` is the path the run was given rather than the empty string the schema forbids, and unknown positions are `0` rather than `null`, which is what the schema requires and what spec/diagnostics.md defines `0` to mean. A clean run emits the envelope too, so a consumer parses one shape either way. The MedUI Studio DTO is deliberately unchanged. Its `/api/screens` body is an editor API whose frontend reads snake_case throughout (screen_name, color_token, stream_source); it is not the shared envelope, and reshaping it would break that frontend to satisfy a schema it was never claiming to meet. The envelope belongs to the checking tool, which is where it now is. The new test validates the emitted JSON against the schema in the *pinned* checkout rather than a copy, so a required member added upstream fails here instead of silently making the output non-conformant. Verified by mutation: an undeclared member, a null position, and an empty file each fail it, and a missing checkout fails it under CI. serde_json is already reviewed SOUP; docs/governance/soup-register.toml records the new integration path. --- .DS_Store | Bin 0 -> 8196 bytes Cargo.lock | 1 + .../tests/shared_conformance.rs | 77 ++++++++---- docs/governance/soup-register.toml | 6 +- medui-conformance.toml | 12 +- tools/trustsc-medui-check/Cargo.toml | 1 + tools/trustsc-medui-check/src/main.rs | 83 +++++++++++-- tools/trustsc-medui-check/tests/cli.rs | 110 ++++++++++++++++++ 8 files changed, 250 insertions(+), 40 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..677eeb00e693dd08a6e9338ffb68e54e964d6eb6 GIT binary patch literal 8196 zcmeHMzi$&U6n+Oub5SZ(2_yoj;v_m(i6|RGS_Lscr!x0Pel!6kTxin5z>xodjfFn| zAqH4M3^0L21xRd2Yz&NSEFkec+qpdFE)fa?DAhj3SiIXUf533qlCgblb#?M|b@EJP&zw*^6&>{g1t+hhtt*`ZPJy@re0I;!GF7QXJM#SA z?r1PB31WzLST0vuVFe!l{Zheylzy|CgsS}ps?+4#f&ObxnDJ$;j4e2cfP zNT1~J@Kt8(OkQz_>bApS^d!F(_uNyC%Q~pI)PxchD>@xtj3Xq6_2&yemrh1Hh;}5C z@hFRrUi5s7NDa9|J*v|lbuC7z#vvHRFp|@W&1h^Aa6^42;VfS1ZG@ybaO&b$2QQnG zfAD0~FZry_7YB32YC|eC4rB4~KWH9RsIsHfv3caqK2|)0U-Ec)D0os7tBX9@(Z)1kE@NCDY8?O;RhLJqJ zT#I-l;D%aE!dblZZkxqdRHvKBgVCv3Gk5OoMKDW1Np27BMcfjRLw1vq7QajZf$0?H zZb-YBH@BhQ9(Zo?y(JwWx8UhOQRd&n`(3O<(AMHlFPhV}BK!B_S=7HN_{iDvXDwO! z=<%CF&si59MQaUyxBmG)dT#k;pY9%8`MRms;StPmw8mj1kB?m*CQ5@xh+k`DW@oQ{ zx4n|Xc&|Z1jgAo&)168Qa$u9;Cl;5irGm>-K*hE4Tl% I3bT=Z0ZP3WZ2$lO literal 0 HcmV?d00001 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-ui-dsl-authoring/tests/shared_conformance.rs b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs index 7391ca4..ae0c597 100644 --- a/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs +++ b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs @@ -13,6 +13,9 @@ //! - 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 @@ -126,30 +129,51 @@ fn assert_diagnostics(case: &Case, actual: &[Diagnostic], manifest: &Manifest) { "{}: diagnostic code (message was {:?})", case.id, actual.message ); - // `spec/diagnostics.md`: positions are 1-based and `0` means unknown. - assert_eq!( - i64::from(actual.line.unwrap_or(0)), - expected.line, - "{}: diagnostic line", - case.id - ); - + // `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.column.unwrap_or(0)), - expected.column, - "{}: diagnostic column", - case.id - ), - // Not "columns are unchecked" but "columns are known-absent": the moment the parser - // starts reporting one, this fails and forces `positions = "full"` and a real check. - Positions::LineOnly => assert!( - actual.column.is_none(), - "{}: medui-conformance.toml declares positions = \"line-only\", but the parser \ - reported column {:?}. Set positions = \"full\" so the pinned column {} is \ - actually checked.", + 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 ), } @@ -183,12 +207,15 @@ fn conformance_root() -> Option { // medui-conformance.toml // ------------------------------------------------------------------------------------------- +/// The declared diagnostic position precision from `spec/diagnostics.md`. #[derive(Debug, Clone, Copy, Eq, PartialEq)] enum Positions { - /// Diagnostics carry exact 1-based UTF-8 byte columns; pinned columns are checked. + /// Line and exact 1-based UTF-8 byte column; both pinned positions are checked. Full, - /// Diagnostics carry no column at all; see the key's comment in `medui-conformance.toml`. + /// 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)] @@ -229,8 +256,10 @@ impl Manifest { positions = Some(match unquote(path, index, value) { "full" => Positions::Full, "line-only" => Positions::LineOnly, + "none" => Positions::None, other => panic!( - "{}:{}: positions must be \"full\" or \"line-only\", got {other:?}", + "{}:{}: positions must be \"full\", \"line-only\" or \"none\", got \ + {other:?}", path.display(), index + 1 ), 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 index 52c996a..c488784 100644 --- a/medui-conformance.toml +++ b/medui-conformance.toml @@ -3,13 +3,13 @@ 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 = "763499016fdf16e9ba697cc938647ea67e8f8145" +commit = "f22f6046be46451ea3b7f56a3f36a220279037d8" # 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"] -# How precisely this implementation can locate a diagnostic. `parse_screen` is line-oriented and -# trims each line before matching, so no column survives to `Diagnostic::column`; the shared cases -# nonetheless pin one. `line-only` records that deviation explicitly instead of dropping the -# assertion: the harness then *requires* every diagnostic to carry no column, so the day a -# positioned lexer lands the suite fails until this is set to `full` and the columns are checked. +# 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 fb43c06..75cd2e0 100644 --- a/tools/trustsc-medui-check/src/main.rs +++ b/tools/trustsc-medui-check/src/main.rs @@ -3,11 +3,15 @@ //! //! 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, + CompileOptions, Diagnostic, ImagePackages, Severity, TextPackages, compile_screen_definition, parse_medui_source, }; @@ -17,12 +21,33 @@ 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(); + for arg in &args { + match arg.as_str() { + "--format=text" => format = Format::Text, + "--format=json" => format = Format::Json, + other if other.starts_with("--") => { + eprintln!("trustsc-medui-check: unknown option {other}"); + return ExitCode::from(2); + } + other => positional.push(other), + } + } + let path = match positional.as_slice() { + [path] => *path, _ => { - eprintln!("usage: trustsc-medui-check "); + eprintln!("usage: trustsc-medui-check [--format=text|json] "); return ExitCode::from(2); } }; @@ -38,7 +63,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; } }; @@ -75,16 +100,60 @@ 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 } } } +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, diagnostic.column) { diff --git a/tools/trustsc-medui-check/tests/cli.rs b/tools/trustsc-medui-check/tests/cli.rs index fdfb931..a9b6498 100644 --- a/tools/trustsc-medui-check/tests/cli.rs +++ b/tools/trustsc-medui-check/tests/cli.rs @@ -19,6 +19,14 @@ 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 a_valid_screen_prints_ok_and_exits_zero() { let path = repo_root().join("examples/hello_world/hello_world.medui"); @@ -102,3 +110,105 @@ 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 file = TempMeduiFile::new(&original.replace("hello-world-label", "hello world label")); + let output = run_json(file.path()); + assert!(!output.status.success()); + + 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)" + ); + } +} From c93a05a976ad05a4f6c9157f19484a1e308bb5cc Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sat, 15 Aug 2026 19:18:21 +0200 Subject: [PATCH 5/7] Re-pin to c8cc45e Review of Compliatory/MedUI#9 specified the consumer manifest and fixed the position table, whose last column read as a constraint on the fixture rather than on the reported diagnostic. This harness already implemented it the intended way and already rejects unknown manifest keys, which the contract now requires, so only the pin moves. --- .DS_Store | Bin 8196 -> 8196 bytes medui-conformance.toml | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.DS_Store b/.DS_Store index 677eeb00e693dd08a6e9338ffb68e54e964d6eb6..0e625079d3323671437713edb8b61dba7fcf23b7 100644 GIT binary patch delta 107 zcmZp1XmQxERUl4IJdA;XfrUYjA)O(Up(Hoo#U&{xKM5$t@$_fkrUZ!-j;Qh}aQS;* cW!Iz27i1U)C+FuD0QE31s5)#G7W~Ku048f3ga7~l delta 107 zcmZp1XmQxERUl5b(3^pQfrUYjA)O(Up(Hoo#U&{xKM5$tvHT!=ytKp#M^yO~yz&JZ WhQZ1CxdlKy3=GN}HVX@W Date: Sat, 15 Aug 2026 20:59:19 +0200 Subject: [PATCH 6/7] Address MedUI contract review feedback --- .DS_Store | Bin 8196 -> 0 bytes .github/workflows/ci.yml | 3 +- .gitignore | 1 + crates/trustsc-core/src/lib.rs | 34 ++++ .../src/diagnostic.rs | 57 +++--- crates/trustsc-ui-dsl-authoring/src/lib.rs | 171 ++++++++++-------- .../tests/shared_conformance.rs | 32 ++++ ...DR-008-deterministic-medui-dsl-boundary.md | 2 +- ...dui-compilation-and-generated-artifacts.md | 2 +- ...ty-monitor-and-vulkan-viewport-contract.md | 2 +- tools/trustsc-medui-check/src/main.rs | 69 ++++++- tools/trustsc-medui-check/tests/cli.rs | 31 +++- .../trustsc-medui-studio/frontend/dist/app.js | 17 +- .../frontend/dist/styles.css | 14 ++ .../trustsc-medui-studio/frontend/src/api.ts | 6 +- .../trustsc-medui-studio/frontend/src/app.ts | 17 +- .../frontend/src/styles.css | 14 ++ 17 files changed, 339 insertions(+), 133 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 0e625079d3323671437713edb8b61dba7fcf23b7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMziSjh6n?AsV~-0GP)HP_Tf{abm~796fA8-1O>l0Gq?BVb}z_TDCf*E^Ok+z%=_k>*%@Yzh`goU`W(?D z5&6h$$IB=(68kx)(h>7!7S=<3qFt&}BWljAtj8&|d*Kvt3OEIv0!{&^z`vjX_H0i6 zfPG(kUFj5X3jCJ}@cIxSvki^yXsebE6zT{7o5O3B@QibSsuLI+8r#uURYjZn^x&DQ zo;hN8x;p#;!(l^XJKE~%IDi;UZ|}rodQmQv;ur~FVYOHQ$%a> z{N8G7FfIvFh*n&w)S|cskNx<)(tCc*el zPh62c$>G!YJCCZ9ibGPj75Acl_&T-U@3-QfRdHDd6_+-lM9qp$$EOgz4uefP=mH;+hUY!9)M8_BRQQ|O~xhz*VE@PoW(0&MMx@u z(>8t$@Ul7id;9%<$!BqFt~*z(Hl#v>FcuI0jpnfqRo0X`Hjna|hl+>rOCHY-1P=?- z(_|3F;xYDxdE_ukF}@(1L$PyI`egitQ|G!mBz2_*S$->SNyYUs0=Llr7G_9646*VE!KoW)D;wk3Q;4Z4Bc9i6&0a| zz{^!uDof~_Ia{ZC$!F~Vxr)q*aUE?{6%-8N_v$zfoBUyj=fL{ZygY*|J0*2Uc P-Tu#G<@SG8VKmY&o$VQ1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7863cca..5d1d9c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: id: medui-contract run: | set -euo pipefail - commit="$(sed -n 's/^commit = "\([0-9a-f]\{40\}\)"$/\1/p' medui-conformance.toml)" + 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 @@ -36,6 +36,7 @@ jobs: repository: Compliatory/MedUI ref: ${{ steps.medui-contract.outputs.commit }} path: .medui-conformance + persist-credentials: false - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable 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/crates/trustsc-core/src/lib.rs b/crates/trustsc-core/src/lib.rs index 7817414..f12a703 100644 --- a/crates/trustsc-core/src/lib.rs +++ b/crates/trustsc-core/src/lib.rs @@ -8,6 +8,8 @@ pub type TrustScResult = Result; pub struct ValidationError { message: String, code: Option<&'static str>, + line: Option, + column: Option, } impl ValidationError { @@ -15,6 +17,8 @@ impl ValidationError { Self { message: message.into(), code: None, + line: None, + column: None, } } @@ -27,13 +31,32 @@ impl ValidationError { 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 { @@ -172,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 354765f..53f63fc 100644 --- a/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs +++ b/crates/trustsc-ui-dsl-authoring/src/diagnostic.rs @@ -14,7 +14,7 @@ pub enum Severity { pub struct Diagnostic { /// Stable implementation-neutral identity from `Compliatory/MedUI`. pub code: &'static str, - /// Repository-relative source file when the caller knows it; empty for in-memory input. + /// Source path supplied by the caller; empty for in-memory input. pub file: String, pub message: String, pub line: Option, @@ -32,14 +32,11 @@ impl Diagnostic { /// "may be reworded" while a code's meaning is stable, so inferring one from the other would /// make a stable identity depend on prose. /// - /// The line number is still recovered from the message: every parser error embeds it as - /// `line {N}` somewhere in the text (not always at the end — e.g. - /// `"component at line {n} must declare \`id\`"`). That stays message-coupled until the - /// line-oriented parser is replaced by a positioned lexer, which is also what would supply - /// the column the shared cases pin. + /// 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 @@ -47,8 +44,8 @@ impl Diagnostic { code: error.code().unwrap_or(code::UNEXPECTED_TOKEN), file: String::new(), message, - line, - column: None, + line: error.line(), + column: error.column(), severity: Severity::Error, fix_hint: String::new(), } @@ -111,18 +108,13 @@ pub(crate) fn coded(code: &'static str, message: impl Into) -> Validatio ValidationError::with_code(code, message) } -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 +/// 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)] @@ -130,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 30bb227..47fca0c 100644 --- a/crates/trustsc-ui-dsl-authoring/src/lib.rs +++ b/crates/trustsc-ui-dsl-authoring/src/lib.rs @@ -132,7 +132,7 @@ pub use catalog::{ pub use serialize::serialize_screen; pub use diagnostic::{Diagnostic, Severity, code}; -use diagnostic::coded; +use diagnostic::{coded, coded_at}; pub fn compile_medui_file_to_rust_module( input_path: impl AsRef, @@ -187,7 +187,8 @@ pub fn compile_medui_source_to_rust( code::UNEXPECTED_TOKEN, "compilation failed with no diagnostics", ), - [only] => coded(only.code, only.message.clone()), + [only] => coded(only.code, only.message.clone()) + .with_position(only.line, only.column), many => coded( code::UNEXPECTED_TOKEN, many.iter() @@ -247,7 +248,8 @@ fn parse_screen(source: &str) -> TrustScResult { .collect::>(); if lines.len() < 3 { - return Err(coded( + 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", )); @@ -278,7 +280,7 @@ fn parse_screen(source: &str) -> TrustScResult { let (line_number, line) = &lines[cursor]; if line == "}" { if cursor != lines.len() - 1 { - return Err(coded(code::UNEXPECTED_TOKEN, format!( + return Err(coded_at(*line_number, code::UNEXPECTED_TOKEN, format!( "unexpected content after screen closing brace at line {line_number}" ))); } @@ -293,7 +295,7 @@ fn parse_screen(source: &str) -> TrustScResult { if line == "Row {" { if pending_safety.is_some() { - return Err(coded(code::FORBIDDEN_CONSTRUCT, format!( + return Err(coded_at(*line_number, code::FORBIDDEN_CONSTRUCT, format!( "@safety_critical cannot annotate a Row container at line {line_number}" ))); } @@ -327,7 +329,8 @@ fn parse_screen(source: &str) -> TrustScResult { } if items.is_empty() { - return Err(coded( + return Err(coded_at( + *screen_line, code::MISSING_FIELD, "MedUI screen must declare at least one component", )); @@ -371,7 +374,7 @@ fn parse_row( } if line == "Row {" { - return Err(coded(code::NESTED_ROW, format!( + return Err(coded_at(*line_number, code::NESTED_ROW, format!( "nested Row containers are not supported at line {line_number}" ))); } @@ -411,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(*line_number, code::UNEXPECTED_TOKEN, format!( "invalid Row property `{property_line}` at line {line_number}" )) })?; @@ -425,7 +428,7 @@ fn parse_row( background = Some(parse_non_empty(*line_number, "background", value.trim())?) } other => { - return Err(coded(code::UNKNOWN_FIELD, format!( + return Err(coded_at(*line_number, code::UNKNOWN_FIELD, format!( "unsupported Row property `{other}` at line {line_number}" ))); } @@ -434,19 +437,19 @@ fn parse_row( } if !closed { - return Err(coded(code::UNEXPECTED_TOKEN, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(coded(code::MISSING_FIELD, format!( + return Err(coded_at(row_line_number, code::MISSING_FIELD, format!( "Row {id} must contain at least one component" ))); } @@ -469,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "expected `Screen {{` at line {line_number}" )) })?; @@ -481,13 +484,14 @@ fn parse_layout(line_number: usize, line: &str) -> TrustScResult TrustScResult LayoutKind::Vertical, "Horizontal" => LayoutKind::Horizontal, other => { - return Err(coded(code::UNREGISTERED, format!( + return Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported layout `{other}` at line {line_number}" ))) } @@ -517,13 +521,14 @@ 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded( + coded_at( + line_number, code::UNEXPECTED_TOKEN, format!("invalid layout property `{entry}` at line {line_number}"), ) @@ -538,7 +543,7 @@ fn parse_safety_critical(line_number: usize, line: &str) -> TrustScResult TrustScResult Ok(CvCheckKind::Bounds), "ColorHash" => Ok(CvCheckKind::ColorHash), - other => Err(coded(code::UNKNOWN_CV_CHECK, 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(coded(code::MISSING_FIELD, 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" ))); } @@ -582,7 +587,8 @@ fn parse_component_start(line_number: usize, line: &str) -> TrustScResult TrustScResult Ok(ComponentKind::Image), "Button" => Ok(ComponentKind::Button), "TextInput" => Ok(ComponentKind::TextInput), - other => Err(coded(code::UNKNOWN_COMPONENT, format!( + other => Err(coded_at(line_number, code::UNKNOWN_COMPONENT, format!( "unsupported component `{other}` at line {line_number}" ))), } @@ -631,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(*property_line_number, code::UNEXPECTED_TOKEN, format!( "invalid property `{property_line}` at line {property_line_number}" )) })?; @@ -672,7 +678,7 @@ fn parse_component_properties( } "charset" => charset = Some(parse_charset(*property_line_number, value)?), other => { - return Err(coded(code::UNKNOWN_FIELD, format!( + return Err(coded_at(*property_line_number, code::UNKNOWN_FIELD, format!( "unsupported property `{other}` at line {property_line_number}" ))) } @@ -680,17 +686,17 @@ fn parse_component_properties( } let id = id.ok_or_else(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(coded(code::LAYOUT_OVERFLOW, format!( + return Err(coded_at(line_number, code::LAYOUT_OVERFLOW, format!( "component {id}: `position` requires fixed `width`/`height` — Fill is flow-only" ))); } @@ -698,77 +704,77 @@ fn parse_component_properties( let kind = match component_kind { ComponentKind::CriticalButton => NodeKind::CriticalButton { requirement_id: requirement_id.ok_or_else(|| { - coded(code::MISSING_FIELD, format!( + coded_at(line_number, code::MISSING_FIELD, format!( "CriticalButton {id} must declare `requirement`" )) })?, label_text_key: label_text_key.ok_or_else(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, format!( + coded_at(line_number, code::MISSING_FIELD, format!( "NumericDisplay {id} must declare `requirement`" )) })?, template_id: template_id.ok_or_else(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(coded(code::UNREGISTERED, format!( + return Err(coded_at(line_number, code::UNREGISTERED, format!( "StatusIndicator {id} declares {} states but {} colors", state_text_keys.len(), color_tokens.len() @@ -776,13 +782,13 @@ fn parse_component_properties( } NodeKind::StatusIndicator { requirement_id: requirement_id.ok_or_else(|| { - coded(code::MISSING_FIELD, format!( + coded_at(line_number, code::MISSING_FIELD, format!( "StatusIndicator {id} must declare `requirement`" )) })?, source: { let (source_line, raw) = source.ok_or_else(|| { - coded(code::MISSING_FIELD, format!( + coded_at(line_number, code::MISSING_FIELD, format!( "StatusIndicator {id} must declare `source`" )) })?; @@ -795,27 +801,27 @@ fn parse_component_properties( ComponentKind::Image => NodeKind::Image { image_id: { let (source_line, raw) = source.ok_or_else(|| { - coded(code::MISSING_FIELD, 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(coded(code::FORBIDDEN_CONSTRUCT, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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)? }, @@ -824,25 +830,25 @@ fn parse_component_properties( } ComponentKind::TextInput => { if on_press.is_some() { - return Err(coded(code::FORBIDDEN_CONSTRUCT, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, 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(|| { - coded(code::MISSING_FIELD, format!("TextInput {id} must declare `color`")) + coded_at(line_number, code::MISSING_FIELD, format!("TextInput {id} must declare `color`")) })?, requirement_id, } @@ -862,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(coded(code::UNEXPECTED_TOKEN, format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -870,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(coded(code::UNEXPECTED_TOKEN, format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} contains unsupported characters at line {line_number}" ))); } @@ -880,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(coded(code::UNEXPECTED_TOKEN, format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -889,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(coded(code::UNEXPECTED_TOKEN, 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(coded(code::UNEXPECTED_TOKEN, format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must not be empty at line {line_number}" ))); } @@ -909,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "text references must use t(\"key\") at line {line_number}" )) })?; @@ -920,7 +926,7 @@ fn parse_system_event(line_number: usize, raw: &str) -> TrustScResult Ok(SystemEvent::NoOp), "SystemEvent.TriggerHalt" => Ok(SystemEvent::TriggerHalt), - other => Err(coded(code::UNREGISTERED, format!( + other => Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported system event `{other}` at line {line_number}" ))), } @@ -930,7 +936,7 @@ fn parse_clock_format(line_number: usize, raw: &str) -> TrustScResult Ok(ClockFormat::TimeSeconds), "DateTimeSeconds" => Ok(ClockFormat::DateTimeSeconds), - other => Err(coded(code::UNREGISTERED, format!( + other => Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported clock format `{other}` at line {line_number}" ))), } @@ -939,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(|_| { - coded(code::UNEXPECTED_TOKEN, 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(coded(code::UNEXPECTED_TOKEN, format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "max_length must be greater than zero at line {line_number}" ))); } @@ -956,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(coded(code::UNREGISTERED, format!( + other => Err(coded_at(line_number, code::UNREGISTERED, format!( "unsupported charset `{other}` at line {line_number}; approved charsets are: AsciiText" ))), } @@ -970,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must be a [..] list at line {line_number}" )) })?; @@ -981,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(coded(code::MISSING_FIELD, format!( + return Err(coded_at(line_number, code::MISSING_FIELD, format!( "{field_name} must declare at least one entry at line {line_number}" ))); } @@ -1009,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "Image source must use `img(\"IMAGE-ID\")` at line {line_number}" )) })?; @@ -1026,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(coded(code::UNEXPECTED_TOKEN, format!( + return Err(coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must be greater than zero at line {line_number}" ))); } @@ -1039,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must use a px unit at line {line_number}" )) })? .parse::() .map_err(|_| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "{field_name} must be a non-negative integer px value at line {line_number}" )) }) @@ -1054,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "position must be `px, px` at line {line_number}" )) })?; @@ -1066,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(|| { - coded(code::UNEXPECTED_TOKEN, format!( + coded_at(line_number, code::UNEXPECTED_TOKEN, format!( "surface must be `px, px` at line {line_number}" )) })?; @@ -3607,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 index ae0c597..ccdfa87 100644 --- a/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs +++ b/crates/trustsc-ui-dsl-authoring/tests/shared_conformance.rs @@ -26,6 +26,7 @@ use std::{ collections::BTreeSet, fs, path::{Path, PathBuf}, + process::Command, }; use trustsc_ui_dsl_authoring::{Diagnostic, parse_medui_source}; @@ -50,6 +51,7 @@ fn pinned_shared_conformance_cases() { let Some(root) = conformance_root() else { return; }; + assert_checkout_matches(&root, &manifest.commit); let cases = load_cases(&root); assert!( @@ -203,6 +205,36 @@ fn conformance_root() -> Option { } } +/// 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 // ------------------------------------------------------------------------------------------- diff --git a/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md b/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md index dd955e6..4f4554e 100644 --- a/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md +++ b/docs/adr/ADR-008-deterministic-medui-dsl-boundary.md @@ -7,7 +7,7 @@ ## Shared decision identity This TrustSC decision implements -[`MEDUI-DEC-001`](https://github.com/Compliatory/MedUI/blob/763499016fdf16e9ba697cc938647ea67e8f8145/decisions/MEDUI-DEC-001-build-time-compilation.md) +[`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. 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 7fdf7f4..e00fddf 100644 --- a/docs/adr/ADR-009-medui-compilation-and-generated-artifacts.md +++ b/docs/adr/ADR-009-medui-compilation-and-generated-artifacts.md @@ -7,7 +7,7 @@ ## Shared decision identity This record is TrustSC's Rust realization of -[`MEDUI-DEC-003`](https://github.com/Compliatory/MedUI/blob/763499016fdf16e9ba697cc938647ea67e8f8145/decisions/MEDUI-DEC-003-compiled-screen-semantics.md). +[`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. 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 a537372..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,7 +1,7 @@ # 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/763499016fdf16e9ba697cc938647ea67e8f8145/decisions/MEDUI-DEC-004-safety-and-goldens.md). +[`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 diff --git a/tools/trustsc-medui-check/src/main.rs b/tools/trustsc-medui-check/src/main.rs index 75cd2e0..cf17ecf 100644 --- a/tools/trustsc-medui-check/src/main.rs +++ b/tools/trustsc-medui-check/src/main.rs @@ -11,8 +11,8 @@ use std::process::ExitCode; use trustsc_ui_dsl_authoring::{ - CompileOptions, Diagnostic, ImagePackages, Severity, 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 @@ -33,21 +33,31 @@ fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); 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("--") => { - eprintln!("trustsc-medui-check: unknown option {other}"); - return ExitCode::from(2); + 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 [--format=text|json] "); + 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); } }; @@ -55,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; } }; @@ -71,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; } }; @@ -86,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; } }; @@ -115,6 +145,27 @@ fn main() -> ExitCode { } } +/// 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), diff --git a/tools/trustsc-medui-check/tests/cli.rs b/tools/trustsc-medui-check/tests/cli.rs index a9b6498..57109c4 100644 --- a/tools/trustsc-medui-check/tests/cli.rs +++ b/tools/trustsc-medui-check/tests/cli.rs @@ -27,6 +27,23 @@ fn run_json(path: &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"); @@ -136,9 +153,19 @@ fn json_output_satisfies_the_pinned_diagnostic_schema() { // 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 file = TempMeduiFile::new(&original.replace("hello-world-label", "hello world label")); + 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()); + 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"); diff --git a/tools/trustsc-medui-studio/frontend/dist/app.js b/tools/trustsc-medui-studio/frontend/dist/app.js index 19a1ee3..40f9dbd 100644 --- a/tools/trustsc-medui-studio/frontend/dist/app.js +++ b/tools/trustsc-medui-studio/frontend/dist/app.js @@ -73,7 +73,12 @@ function renderDiagnostics(container, diagnostics) { const location = diagnostic.line !== null ? `line ${diagnostic.line}: ` : ""; return el("li", {}, [`${location}${diagnostic.message}`]); }); - 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 +260,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..8692310 100644 --- a/tools/trustsc-medui-studio/frontend/src/app.ts +++ b/tools/trustsc-medui-studio/frontend/src/app.ts @@ -105,7 +105,12 @@ function renderDiagnostics(container: HTMLElement, diagnostics: Diagnostic[]): v const location = diagnostic.line !== null ? `line ${diagnostic.line}: ` : ""; return el("li", {}, [`${location}${diagnostic.message}`]); }); - 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 +316,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; From 91b4f316e243fe935e0b4e89fb5cd5fdc6acb0ec Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sat, 15 Aug 2026 21:05:59 +0200 Subject: [PATCH 7/7] Render MedUI diagnostic metadata --- tools/trustsc-medui-studio/frontend/dist/app.js | 10 ++++++++-- tools/trustsc-medui-studio/frontend/src/app.ts | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/tools/trustsc-medui-studio/frontend/dist/app.js b/tools/trustsc-medui-studio/frontend/dist/app.js index 40f9dbd..e5226e9 100644 --- a/tools/trustsc-medui-studio/frontend/dist/app.js +++ b/tools/trustsc-medui-studio/frontend/dist/app.js @@ -70,8 +70,14 @@ 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}`]); }); const severity = diagnostics.some((diagnostic) => diagnostic.severity === "Error") ? "error" diff --git a/tools/trustsc-medui-studio/frontend/src/app.ts b/tools/trustsc-medui-studio/frontend/src/app.ts index 8692310..345a77a 100644 --- a/tools/trustsc-medui-studio/frontend/src/app.ts +++ b/tools/trustsc-medui-studio/frontend/src/app.ts @@ -102,8 +102,14 @@ 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}`]); }); const severity = diagnostics.some((diagnostic) => diagnostic.severity === "Error") ? "error"