Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .claude/skills/medui-authoring/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
21 changes: 21 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,25 @@ jobs:
- name: Check out repository
uses: actions/checkout@v4

- name: Resolve the pinned MedUI contract commit
id: medui-contract
run: |
set -euo pipefail
commit="$(sed -n 's/^[[:space:]]*commit[[:space:]]*=[[:space:]]*"\([0-9A-Fa-f]\{40\}\)"[[:space:]]*$/\1/p' medui-conformance.toml)"
if [ -z "$commit" ]; then
echo "medui-conformance.toml has no 40-character commit pin" >&2
exit 1
fi
echo "commit=$commit" >> "$GITHUB_OUTPUT"

- name: Check out pinned MedUI conformance contract
uses: actions/checkout@v4
with:
repository: Compliatory/MedUI
ref: ${{ steps.medui-contract.outputs.commit }}
path: .medui-conformance
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
persist-credentials: false

- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@stable

Expand All @@ -34,6 +53,8 @@ jobs:
run: cargo build --locked --workspace

- name: Run test suite
env:
MEDUI_CONFORMANCE_DIR: ${{ github.workspace }}/.medui-conformance
run: cargo test --locked --quiet

- name: Lint regulatory citations and Justification blocks (ADR-020)
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/target
.DS_Store
CLAUDE.md
.claude/settings.local.json

Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

53 changes: 53 additions & 0 deletions crates/trustsc-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,56 @@ pub type TrustScResult<T> = Result<T, ValidationError>;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ValidationError {
message: String,
code: Option<&'static str>,
line: Option<u32>,
column: Option<u32>,
}

impl ValidationError {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
code: None,
line: None,
column: None,
}
}

/// An error tagged with a stable machine-readable identity assigned by the producing crate.
///
/// The identity is deliberately opaque here: this crate does not own any code registry, it
/// only carries the tag so a caller can route on it without re-deriving meaning from
/// [`Display`] output, which is free to be reworded.
pub fn with_code(code: &'static str, message: impl Into<String>) -> Self {
Self {
message: message.into(),
code: Some(code),
line: None,
column: None,
}
}

/// Attaches a structured source position supplied by the producing crate.
pub fn with_position(mut self, line: Option<u32>, column: Option<u32>) -> 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<u32> {
self.line
}

/// The 1-based source column assigned at the raise site, when known.
pub fn column(&self) -> Option<u32> {
self.column
}
}

impl Display for ValidationError {
Expand Down Expand Up @@ -153,4 +195,15 @@ mod tests {

assert_eq!(error.to_string(), "manufacturer must not be empty");
}

#[test]
fn validation_error_carries_structured_metadata() {
let error = ValidationError::with_code("TEST-E001", "message mentioning line 99")
.with_position(Some(7), Some(3));

assert_eq!(error.code(), Some("TEST-E001"));
assert_eq!(error.line(), Some(7));
assert_eq!(error.column(), Some(3));
assert_eq!(error.to_string(), "message mentioning line 99");
}
}
132 changes: 98 additions & 34 deletions crates/trustsc-ui-dsl-authoring/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,68 +6,132 @@ use trustsc_core::ValidationError;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Severity {
Error,
Warning,
Note,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Diagnostic {
/// Stable implementation-neutral identity from `Compliatory/MedUI`.
pub code: &'static str,
/// Source path supplied by the caller; empty for in-memory input.
pub file: String,
pub message: String,
pub line: Option<u32>,
/// 1-based UTF-8 byte column, or `None` when the legacy parser cannot locate it precisely.
pub column: Option<u32>,
pub severity: Severity,
pub fix_hint: String,
}

impl Diagnostic {
/// Extracts the line number from a [`ValidationError`]'s message, if present. Every parser
/// error in this crate embeds the source line as `line {N}` somewhere in the message (not
/// always at the end — e.g. `"component at line {n} must declare \`id\`"`), so this scans for
/// the last `line ` occurrence followed by a run of ASCII digits rather than assuming a fixed
/// position.
/// Builds the shared diagnostic envelope from an error raised inside this crate.
///
/// The code is read from the error itself — assigned at the point the condition was
/// detected — never re-derived from the message. `spec/diagnostics.md` states that a message
/// "may be reworded" while a code's meaning is stable, so inferring one from the other would
/// make a stable identity depend on prose.
///
/// Source positions are carried independently of the human-readable message. The current
/// line-oriented parser supplies a line but no column; compilation failures without a
/// source anchor leave both absent.
pub fn from_validation_error(error: &ValidationError) -> Diagnostic {
let message = error.to_string();
let line = extract_line_number(&message);
Diagnostic {
// An untagged error means a raise site in this crate forgot its code, or an error
// crossed in from another crate. `assigns_a_code_to_every_raise_site` covers the
// first; the fallback keeps the envelope well-formed for the second.
code: error.code().unwrap_or(code::UNEXPECTED_TOKEN),
file: String::new(),
message,
line,
line: error.line(),
column: error.column(),
severity: Severity::Error,
fix_hint: String::new(),
}
}
}

fn extract_line_number(message: &str) -> Option<u32> {
let mut search = message;
let mut found = None;
while let Some(index) = search.find("line ") {
let after = &search[index + "line ".len()..];
let digits: String = after.chars().take_while(|c| c.is_ascii_digit()).collect();
if !digits.is_empty() {
found = digits.parse().ok();
}
search = &search[index + "line ".len()..];
}
found
/// The `MEDUI-E###` identities from the pinned contract's `spec/diagnostics.md`, named by meaning
/// so a raise site reads as the condition it detects.
///
/// A code's meaning never changes and a retired number is never reused (`MEDUI-DEC-005`), so
/// these constants are append-only. Codes the contract registers but this implementation never
/// raises — `MEDUI-E004` (source is not UTF-8), `MEDUI-E017` (hardcoded product string),
/// `MEDUI-E053` (dynamic text escapes its charset) — are deliberately absent rather than
/// declared and unused.
pub mod code {
/// `MEDUI-E003` — the `.medui` source could not be read.
pub const SOURCE_UNREADABLE: &str = "MEDUI-E003";
/// `MEDUI-E010` — the source does not parse.
pub const UNEXPECTED_TOKEN: &str = "MEDUI-E010";
/// `MEDUI-E011` — the component name is not in the closed dictionary.
pub const UNKNOWN_COMPONENT: &str = "MEDUI-E011";
/// `MEDUI-E012` — a construct omits a field its schema requires.
pub const MISSING_FIELD: &str = "MEDUI-E012";
/// `MEDUI-E013` — a construct declares a field its schema does not define.
pub const UNKNOWN_FIELD: &str = "MEDUI-E013";
/// `MEDUI-E014` — two nodes resolve to the same id.
pub const DUPLICATE_NODE_ID: &str = "MEDUI-E014";
/// `MEDUI-E015` — a `Row` nests inside another `Row`.
pub const NESTED_ROW: &str = "MEDUI-E015";
/// `MEDUI-E016` — a construct the language forbids in this position.
pub const FORBIDDEN_CONSTRUCT: &str = "MEDUI-E016";
/// `MEDUI-E030` — the theme colour token is not approved.
pub const UNKNOWN_COLOR_TOKEN: &str = "MEDUI-E030";
/// `MEDUI-E031` — the text key does not exist in the approved package.
pub const UNKNOWN_TEXT_KEY: &str = "MEDUI-E031";
/// `MEDUI-E032` — the text key exists but an approved locale has no run for it.
pub const TEXT_KEY_MISSING_LOCALE: &str = "MEDUI-E032";
/// `MEDUI-E050` — rendered text does not fit its box in the worst approved case.
pub const TEXT_BUDGET_EXCEEDED: &str = "MEDUI-E050";
/// `MEDUI-E051` — a node escapes its container or collides with another.
pub const LAYOUT_OVERFLOW: &str = "MEDUI-E051";
/// `MEDUI-E052` — resolved geometry leaves the screen surface.
pub const SURFACE_EXCEEDED: &str = "MEDUI-E052";
/// `MEDUI-E071` — a CV check is not one the contract defines for this node.
pub const UNKNOWN_CV_CHECK: &str = "MEDUI-E071";

/// A condition the pinned registry has no code for, reported as `MEDUI-E010` until one
/// exists.
///
/// `spec/component-model.md` makes unknown image IDs, templates, charsets, clock formats,
/// system events, and layout kinds fatal, but registers a code only for colour tokens
/// (`MEDUI-E030`) and CV checks (`MEDUI-E071`). Marking these sites explicitly keeps them
/// greppable as registry gaps to raise upstream, instead of letting them fall through a
/// catch-all unnoticed.
pub const UNREGISTERED: &str = UNEXPECTED_TOKEN;
}

/// Raises an error carrying the stable identity of the condition that produced it.
pub(crate) fn coded(code: &'static str, message: impl Into<String>) -> ValidationError {
ValidationError::with_code(code, message)
}

/// Raises a parser error with its structured 1-based line position.
pub(crate) fn coded_at(
line_number: usize,
code: &'static str,
message: impl Into<String>,
) -> ValidationError {
coded(code, message).with_position(u32::try_from(line_number).ok(), None)
}

#[cfg(test)]
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);
}
}
Loading
Loading