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: 5 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ jobs:
- name: Build workspace
run: cargo build --locked --workspace

- name: Gate claimed MedUI conformance against the pinned corpus
env:
MEDUI_CONFORMANCE_DIR: ${{ github.workspace }}/.medui-conformance
run: cargo test --locked -p trustsc-ui-dsl-authoring --test shared_conformance -- --nocapture

- name: Run test suite
env:
MEDUI_CONFORMANCE_DIR: ${{ github.workspace }}/.medui-conformance
Expand Down
31 changes: 20 additions & 11 deletions crates/trustsc-ui-dsl-authoring/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,25 @@ impl Diagnostic {
/// 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.
/// these constants are append-only. This is an implementation subset of the `0.3.0-rc.1` registry,
/// not a declaration that every registered diagnostic is implemented. Missing here are:
///
/// - E000/E001/E002: recipe diagnostics (this crate has no recipe reader).
/// - E017: hardcoded product string; the legacy parser instead reports E010.
/// - E033/E034/E035: semantic kind, closed-set member and resource identity; older local
/// diagnostic mappings remain instead of these dedicated identities.
/// - E053: dynamic text escaping its charset.
/// - E054: positioned node without fixed dimensions; the legacy parser reports E051.
/// - E070: a safety-critical annotation without a requirement. In particular, an annotated
/// Button or TextInput with no requirement is currently accepted; this is a behavioral gap,
/// not simply an unnamed error. Semantics, layout and safety remain unclaimed by the harness.
///
/// See `docs/dsl/conformance.md` for the coverage limits at the pinned contract.
pub mod code {
/// `MEDUI-E003` — the `.medui` source could not be read.
pub const SOURCE_UNREADABLE: &str = "MEDUI-E003";
/// `MEDUI-E004` — the source bytes are not valid UTF-8.
pub const SOURCE_NOT_UTF8: &str = "MEDUI-E004";
/// `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.
Expand Down Expand Up @@ -92,14 +104,11 @@ pub mod code {
/// `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.
/// Legacy fallback for conditions without a dedicated raise-site identity in this crate.
///
/// `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.
/// Some now have registered identities in the pinned contract (notably E034 for clock/event
/// members and E035 for image/template IDs); others still lack one. This name records a
/// local implementation gap, not a claim that the shared registry has no matching code.
pub const UNREGISTERED: &str = UNEXPECTED_TOKEN;
}

Expand Down
188 changes: 181 additions & 7 deletions crates/trustsc-ui-dsl-authoring/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![forbid(unsafe_code)]

use std::{
collections::BTreeSet,
fmt::Write as _,
fs,
path::Path,
Expand Down Expand Up @@ -143,14 +144,15 @@ pub fn compile_medui_file_to_rust_module(
) -> TrustScResult<()> {
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| {
let bytes = fs::read(input_path).map_err(|error| {
coded(code::SOURCE_UNREADABLE, format!(
"failed to read MedUI source {}: {error}",
input_path.display()
))
})?;
let source = decode_medui_source(&bytes)?;
let generated =
compile_medui_source_to_rust(&source, options, text_packages, image_packages)?;
compile_medui_source_to_rust(source, options, text_packages, image_packages)?;

if let Some(parent) = output_path.parent() {
fs::create_dir_all(parent).map_err(|error| {
Expand Down Expand Up @@ -201,6 +203,29 @@ pub fn compile_medui_source_to_rust(
Ok(emit_rust_module(&compiled, options.crate_path))
}

/// Parses source bytes, reporting invalid UTF-8 as `MEDUI-E004` before parsing.
/// Diagnostic positions retain the parser's line-only precision, including decoding failures.
/// File-based callers should use this entry point so encoding failures are distinct from I/O.
pub fn parse_medui_bytes(source: &[u8]) -> Result<ScreenDefinition, Vec<Diagnostic>> {
let source = decode_medui_source(source)
.map_err(|error| vec![Diagnostic::from_validation_error(&error)])?;
parse_medui_source(source)
}

fn decode_medui_source(source: &[u8]) -> TrustScResult<&str> {
std::str::from_utf8(source).map_err(|error| {
let line = 1 + source[..error.valid_up_to()]
.iter()
.filter(|&&byte| byte == b'\n')
.count();
coded_at(
line,
code::SOURCE_NOT_UTF8,
"MedUI source is not valid UTF-8",
)
})
}

/// Parses `.medui` source into its AST without compiling it — the entry point a GUI (MedUI
/// Studio, ADR-022) uses to load a screen for editing. The parser is fail-fast (one error stops
/// parsing), so the returned `Vec` currently always has length 1; it is `Vec` rather than a
Expand Down Expand Up @@ -260,6 +285,7 @@ fn parse_screen(source: &str) -> TrustScResult<ScreenDefinition> {
let (layout_line, layout_header) = &lines[1];
let layout = parse_layout(*layout_line, layout_header)?;
let mut items = Vec::new();
let mut node_ids = Vec::new();
let mut pending_safety: Option<SafetyCriticalDefinition> = None;
let mut cursor = 2usize;

Expand Down Expand Up @@ -299,7 +325,7 @@ fn parse_screen(source: &str) -> TrustScResult<ScreenDefinition> {
"@safety_critical cannot annotate a Row container at line {line_number}"
)));
}
let (row, next_cursor) = parse_row(&lines, cursor)?;
let (row, next_cursor) = parse_row(&lines, cursor, &mut node_ids)?;
items.push(ScreenItem::Row(row));
cursor = next_cursor;
continue;
Expand All @@ -324,6 +350,7 @@ fn parse_screen(source: &str) -> TrustScResult<ScreenDefinition> {
component_kind,
pending_safety.take(),
&properties,
&mut node_ids,
)?;
items.push(ScreenItem::Component(node));
}
Expand All @@ -336,6 +363,7 @@ fn parse_screen(source: &str) -> TrustScResult<ScreenDefinition> {
));
}

validate_authored_node_ids(&mut node_ids)?;
Ok(ScreenDefinition {
id: screen_id,
layout,
Expand All @@ -351,6 +379,7 @@ fn parse_screen(source: &str) -> TrustScResult<ScreenDefinition> {
fn parse_row(
lines: &[(usize, String)],
start: usize,
node_ids: &mut Vec<(usize, String)>,
) -> TrustScResult<(RowDefinition, usize)> {
let (row_line_number, _) = &lines[start];
let row_line_number = *row_line_number;
Expand Down Expand Up @@ -406,6 +435,7 @@ fn parse_row(
component_kind,
pending_safety.take(),
&properties,
node_ids,
)?;
children.push(node);
continue;
Expand All @@ -419,7 +449,9 @@ fn parse_row(
))
})?;
match key.trim() {
"id" => id = Some(parse_identifier(*line_number, "Row id", value.trim())?),
"id" => {
id = Some((*line_number, parse_identifier(*line_number, "Row id", value.trim())?));
}
"height" => height = Some(parse_dimension(*line_number, "height", value.trim())?),
"spacing" => {
spacing = Some(parse_px_allowing_zero(*line_number, "spacing", value.trim())?)
Expand All @@ -442,7 +474,7 @@ fn parse_row(
)));
}

let id = id.ok_or_else(|| {
let (id_line, id) = id.ok_or_else(|| {
coded_at(row_line_number, code::MISSING_FIELD, format!("Row at line {row_line_number} must declare `id`"))
})?;
let height = height.ok_or_else(|| {
Expand All @@ -454,6 +486,7 @@ fn parse_row(
)));
}

node_ids.push((id_line, id.clone()));
Ok((
RowDefinition {
id,
Expand Down Expand Up @@ -615,6 +648,7 @@ fn parse_component_properties(
component_kind: ComponentKind,
safety_critical: Option<SafetyCriticalDefinition>,
properties: &[(usize, String)],
node_ids: &mut Vec<(usize, String)>,
) -> TrustScResult<NodeDefinition> {
let mut id = None;
let mut width = None;
Expand Down Expand Up @@ -644,7 +678,12 @@ fn parse_component_properties(
let key = key.trim();
let value = value.trim();
match key {
"id" => id = Some(parse_identifier(*property_line_number, "component id", value)?),
"id" => {
id = Some((
*property_line_number,
parse_identifier(*property_line_number, "component id", value)?,
));
}
"width" => width = Some(parse_dimension(*property_line_number, "width", value)?),
"height" => height = Some(parse_dimension(*property_line_number, "height", value)?),
"requirement" => {
Expand Down Expand Up @@ -685,7 +724,7 @@ fn parse_component_properties(
}
}

let id = id.ok_or_else(|| {
let (id_line, id) = id.ok_or_else(|| {
coded_at(line_number, code::MISSING_FIELD, format!("component at line {line_number} must declare `id`"))
})?;
let width = width.ok_or_else(|| {
Expand Down Expand Up @@ -855,6 +894,7 @@ fn parse_component_properties(
}
};

node_ids.push((id_line, id.clone()));
Ok(NodeDefinition {
id,
width,
Expand All @@ -865,6 +905,25 @@ fn parse_component_properties(
})
}

/// Check only the final ID of each authored node, in declaration order. Repeated `id:`
/// properties retain the parser's last-value-wins behavior; overwritten values reserve nothing.
/// Rows finish parsing after their children, so sort by the effective declaration's source line.
/// The compiled-node check still covers synthetic panels and caller-edited ASTs.
fn validate_authored_node_ids(node_ids: &mut [(usize, String)]) -> TrustScResult<()> {
node_ids.sort_by_key(|(line, _)| *line);
let mut seen = BTreeSet::new();
for (line, id) in node_ids.iter() {
if !seen.insert(id.as_str()) {
return Err(coded_at(
*line,
code::DUPLICATE_NODE_ID,
format!("duplicate node id {id}"),
));
}
}
Ok(())
}

fn parse_identifier(line_number: usize, field_name: &str, raw: &str) -> TrustScResult<String> {
let value = raw.trim();
if value.is_empty() {
Expand Down Expand Up @@ -3442,6 +3501,121 @@ Screen InteractivePanel {
"/../../examples/class_c_monitor/neurosense.medui"
));

#[test]
fn source_bytes_distinguish_encoding_failures_and_preserve_line_precision() {
assert_eq!(
parse_medui_bytes(HELLO_WORLD_MEDUI.as_bytes()),
parse_medui_source(HELLO_WORLD_MEDUI)
);
for source in [
b"\xff".as_slice(),
b"// valid UTF-8: \xc3\xa9\r\n\n\xe2\x82".as_slice(),
] {
let diagnostics =
parse_medui_bytes(source).expect_err("invalid UTF-8 must fail before parsing");
assert_eq!(diagnostics[0].code, code::SOURCE_NOT_UTF8);
assert_eq!(
diagnostics[0].line,
Some(if source[0] == 0xff { 1 } else { 3 })
);
assert_eq!(diagnostics[0].column, None);
}
}

#[test]
fn authored_ids_are_unique_across_rows_and_root_components_at_parse_time() {
let leaf = |id| {
format!(
"Label {{\nid: {id};\nwidth: 10px;\nheight: 10px;\ntext: t(\"STR-X\");\ncolor: Theme.Colors.Title;\n}}\n"
)
};
let row = |id, child| format!("Row {{\nid: {id};\nheight: 10px;\n{} }}\n", leaf(child));
for body in [
format!("{}{}", row("row-a", "shared"), row("row-b", "shared")),
format!("{}{}", leaf("shared"), row("row", "shared")),
format!("{}{}", row("shared", "child-a"), row("shared", "child-b")),
] {
let source = screen_with(&body);
let error = parse_medui_source(&source)
.expect_err("duplicate authored id must fail during parsing");
let second = source
.lines()
.enumerate()
.filter(|(_, line)| line.trim() == "id: shared;")
.nth(1)
.unwrap()
.0
+ 1;
assert_eq!(error[0].code, code::DUPLICATE_NODE_ID);
assert_eq!(error[0].line, Some(second as u32));
assert_eq!(error[0].column, None);
}
}

#[test]
fn overwritten_id_properties_do_not_reserve_authored_names() {
let leaf = |id| {
format!(
"Label {{\nid: {id};\nwidth: 10px;\nheight: 10px;\ntext: t(\"STR-X\");\ncolor: Theme.Colors.Title;\n}}\n"
)
};
let canonical = format!("{}{}", leaf("first"), leaf("second"));
for source in [
canonical.replace("id: first;", "id: second;\nid: first;"),
canonical.replace("id: second;", "id: first;\nid: second;"),
canonical.replace("id: first;", "id: first;\nid: first;"),
] {
assert_eq!(
parse_medui_source(&screen_with(&source))
.expect("overwritten IDs must not collide"),
parse_medui_source(&screen_with(&canonical)).expect("canonical IDs are unique")
);
}
let canonical = format!(
"Row {{\nid: row;\nheight: 10px;\n{} }}\n{}",
leaf("child"),
leaf("other")
);
for source in [
canonical.replace("id: row;", "id: other;\nid: row;"),
canonical.replace("id: row;", "id: child;\nid: row;"),
canonical.replace("id: child;", "id: row;\nid: child;"),
canonical.replace("id: row;", "id: row;\nid: row;"),
canonical
.replace("id: row;", "id: child;")
.replace("\n }", "\nid: row;\n}"),
] {
assert_eq!(
parse_medui_source(&screen_with(&source))
.expect("overwritten IDs must not collide"),
parse_medui_source(&screen_with(&canonical)).expect("canonical IDs are unique")
);
}
}

#[test]
fn final_duplicate_ids_report_the_later_effective_declaration() {
let leaf = "Label {\nid: shared;\nwidth: 10px;\nheight: 10px;\ntext: t(\"STR-X\");\ncolor: Theme.Colors.Title;\n}\n";
for body in [
format!("Row {{\nid: discarded;\nid: shared;\nheight: 10px;\n{leaf}}}\n"),
format!("Row {{\nid: discarded;\nheight: 10px;\n{leaf}id: shared;\n}}\n"),
] {
let source = screen_with(&body);
let last_id_line = source
.lines()
.enumerate()
.filter(|(_, line)| *line == "id: shared;")
.last()
.unwrap()
.0
+ 1;
let errors =
parse_medui_source(&source).expect_err("the final row and child IDs still collide");
assert_eq!(errors[0].code, code::DUPLICATE_NODE_ID);
assert_eq!(errors[0].line, Some(last_id_line as u32));
}
}

#[test]
fn parse_medui_source_is_deterministic_for_example_screens() {
for source in [HELLO_WORLD_MEDUI, NEUROSENSE_MEDUI] {
Expand Down
Loading
Loading