From e6ad2023fbe28949fa7f7288352c4e51ed413a62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Bohn?= Date: Thu, 5 Nov 2026 13:42:24 +0100 Subject: [PATCH 1/6] Parse and preserve unknown header items --- CHANGELOG.md | 4 +++ src/header.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lexer.rs | 10 +++++-- src/lib.rs | 2 +- src/output.rs | 12 +++++++- 5 files changed, 107 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d2f166..e05864d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Added + +- `HeaderItem::Unknown(name, values)` (with `UnknownValue`): unknown header items such as `controllable-AP:` or `spot.state-player:` are now parsed, kept, and written back out instead of being a parse error. Unknown names starting with an uppercase letter log a `tracing` warning. Header names may now contain `.`. + ### Changed - Accessors no longer `debug_assert` header multiplicities that the HOA spec does not require, so they work on valid files without `States:`, `Start:`, `acc-name:` or `AP:`: diff --git a/src/header.rs b/src/header.rs index 83ddb77..1ba6811 100644 --- a/src/header.rs +++ b/src/header.rs @@ -35,6 +35,20 @@ pub enum HeaderItem { Name(String), /// (>=0) Gives the properties of the automaton. Properties(Vec), + /// A header item this crate does not know. The spec allows ignoring those + /// whose name starts with a lowercase letter; they are kept to allow round-tripping. + Unknown(String, Vec), +} + +/// A value of an [`HeaderItem::Unknown`] header item. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum UnknownValue { + /// An integer. + Int(String), + /// A quoted string (without the quotes). + Text(String), + /// An identifier. + Identifier(String), } impl HeaderItem { @@ -130,6 +144,33 @@ fn item() -> impl Parser> { ) .map(HeaderItem::Properties); + const KNOWN: [&str; 9] = [ + "HOA", + "States", + "Start", + "AP", + "Alias", + "Acceptance", + "acc-name", + "tool", + "name", + ]; + let unknown = select! { Token::Header(name) if !KNOWN.contains(&name.as_str()) && name != "properties" => name } + .then( + select! { + Token::Int(i) => UnknownValue::Int(i), + Token::Text(t) => UnknownValue::Text(t), + Token::Identifier(i) => UnknownValue::Identifier(i), + } + .repeated(), + ) + .map(|(name, values)| { + if name.starts_with(|c: char| c.is_ascii_uppercase()) { + tracing::warn!("ignoring unknown header item {name}"); + } + HeaderItem::Unknown(name, values) + }); + chumsky::primitive::choice(( states, acceptance, @@ -140,6 +181,7 @@ fn item() -> impl Parser> { name, tool, properties, + unknown, )) } @@ -296,6 +338,47 @@ mod tests { assert_fails("tool: ltl-translate \"1.2-alpha\""); } + #[test] + fn unknown_items() { + assert_header( + "controllable-AP: 0 1\nspot.state-player: 0 1 1\nFoo: \"x\" bar", + &[ + HeaderItem::Version("v1".into()), + HeaderItem::Unknown( + "controllable-AP".into(), + vec![UnknownValue::Int("0".into()), UnknownValue::Int("1".into())], + ), + HeaderItem::Unknown( + "spot.state-player".into(), + vec![ + UnknownValue::Int("0".into()), + UnknownValue::Int("1".into()), + UnknownValue::Int("1".into()), + ], + ), + HeaderItem::Unknown( + "Foo".into(), + vec![ + UnknownValue::Text("x".into()), + UnknownValue::Identifier("bar".into()), + ], + ), + ], + ); + } + + #[test] + fn unknown_items_round_trip() { + let hoa = "HOA: v1\nStates: 1\nStart: 0\nAP: 0\nAcceptance: 0 t\ncontrollable-AP: 0 1\nspot.state-player: 0\n--BODY--\nState: 0\n--END--"; + let aut = crate::parse_hoa_automata(hoa).remove(0); + let out = crate::output::to_hoa(&aut); + assert!(out.contains("controllable-AP: 0 1\nspot.state-player: 0\n--BODY--")); + assert_eq!( + crate::parse_hoa_automata(&out).remove(0).header(), + aut.header() + ); + } + #[test] fn ariadne() { assert_header( diff --git a/src/lexer.rs b/src/lexer.rs index e5d7753..e7cd8b1 100644 --- a/src/lexer.rs +++ b/src/lexer.rs @@ -64,9 +64,15 @@ pub fn tokenizer() -> impl Parser, Error = Simple let alias = just('@').ignore_then(raw_ident).map(Token::Alias); - let header = ident + // Spot emits header names such as `spot.state-player`, so `.` is allowed here only. + let header = filter(|c: &char| c.is_ascii_alphabetic() || *c == '_') + .chain( + filter(|c: &char| c.is_ascii_alphanumeric() || matches!(*c, '_' | '-' | '.')) + .repeated(), + ) + .collect::() .then_ignore(just(':')) - .map(|header_name| Token::Header(header_name.to_string())); + .map(Token::Header); let body = just("--BODY--").to(Token::BodyStart); let end = just("--END--").to(Token::BodyEnd); diff --git a/src/lib.rs b/src/lib.rs index 4d5f5f1..8fb2716 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,7 +30,7 @@ pub use format::{ }; pub use body::{Body, Edge, State}; -pub use header::{Header, HeaderItem}; +pub use header::{Header, HeaderItem, UnknownValue}; use itertools::Itertools; use lexer::Token; diff --git a/src/output.rs b/src/output.rs index f072a0a..4dba33c 100644 --- a/src/output.rs +++ b/src/output.rs @@ -6,7 +6,7 @@ use itertools::Itertools; use crate::{ AcceptanceAtom, AcceptanceCondition, AcceptanceInfo, AcceptanceName, AcceptanceSignature, AliasName, Edge, HeaderItem, HoaBool, HoaRepresentation, Label, LabelExpression, Property, - State, StateConjunction, + State, StateConjunction, UnknownValue, }; /// Quotes a string for use in HOA, escaping backslashes and double quotes. @@ -82,6 +82,16 @@ impl Display for HeaderItem { HeaderItem::Properties(properties) => { write!(f, "properties: {}", properties.iter().join(" ")) } + HeaderItem::Unknown(name, values) => { + write!(f, "{name}:")?; + for value in values { + match value { + UnknownValue::Int(s) | UnknownValue::Identifier(s) => write!(f, " {s}")?, + UnknownValue::Text(s) => write!(f, " {}", quote(s))?, + } + } + Ok(()) + } } } } From ff7d6c8caabfe33c813c1b85a3f1f6577578463e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Bohn?= Date: Thu, 5 Nov 2026 13:43:49 +0100 Subject: [PATCH 2/6] Accept unknown properties and acc-name values --- CHANGELOG.md | 1 + src/format.rs | 80 +++++++++++++++++++++++++-------------------------- src/header.rs | 27 +++++++++++++---- src/output.rs | 2 ++ 4 files changed, 65 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e05864d..d1cc796 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Changed +- `Property` and `AcceptanceName` gained an `Other(String)` variant, and their `TryFrom` impls became infallible `From`. Unknown `properties:` values (e.g. `semi-deterministic`) and `acc-name:` names (e.g. `Rabin-like`) now parse and are written back verbatim. - Accessors no longer `debug_assert` header multiplicities that the HOA spec does not require, so they work on valid files without `States:`, `Start:`, `acc-name:` or `AP:`: - `HoaRepresentation::aps` returns `&[String]` (was `&Vec`) and is empty when the header has no `AP:`; - `num_aps` returns `u16` (was `u8`, which panicked above 255 APs); diff --git a/src/format.rs b/src/format.rs index 69af549..5617ac5 100644 --- a/src/format.rs +++ b/src/format.rs @@ -206,6 +206,8 @@ pub enum AcceptanceName { All, /// A condition where nothing is accepted. None, + /// Any other name (e.g. Spot's `Rabin-like`), kept verbatim. + Other(String), } impl AcceptanceName { @@ -214,22 +216,20 @@ impl AcceptanceName { } } -impl TryFrom for AcceptanceName { - type Error = String; - - fn try_from(value: String) -> Result { +impl From for AcceptanceName { + fn from(value: String) -> Self { match value.as_str() { - "Buchi" => Ok(AcceptanceName::Buchi), - "generalized-Buchi" => Ok(AcceptanceName::GeneralizedBuchi), - "co-Buchi" => Ok(AcceptanceName::CoBuchi), - "generalized-co-Buchi" => Ok(AcceptanceName::GeneralizedCoBuchi), - "Streett" => Ok(AcceptanceName::Streett), - "Rabin" => Ok(AcceptanceName::Rabin), - "generalized-Rabin" => Ok(AcceptanceName::GeneralizedRabin), - "parity" => Ok(AcceptanceName::Parity), - "all" => Ok(AcceptanceName::All), - "none" => Ok(AcceptanceName::None), - val => Err(format!("Unknown acceptance type: {}", val)), + "Buchi" => AcceptanceName::Buchi, + "generalized-Buchi" => AcceptanceName::GeneralizedBuchi, + "co-Buchi" => AcceptanceName::CoBuchi, + "generalized-co-Buchi" => AcceptanceName::GeneralizedCoBuchi, + "Streett" => AcceptanceName::Streett, + "Rabin" => AcceptanceName::Rabin, + "generalized-Rabin" => AcceptanceName::GeneralizedRabin, + "parity" => AcceptanceName::Parity, + "all" => AcceptanceName::All, + "none" => AcceptanceName::None, + _ => AcceptanceName::Other(value), } } } @@ -257,32 +257,32 @@ pub enum Property { Terminal, Tight, Colored, + /// Any other property (e.g. Spot's `semi-deterministic`), kept verbatim. + Other(String), } -impl TryFrom for Property { - type Error = String; - - fn try_from(value: String) -> Result { +impl From for Property { + fn from(value: String) -> Self { match value.as_str() { - "state-labels" => Ok(Property::StateLabels), - "trans-labels" => Ok(Property::TransLabels), - "implicit-labels" => Ok(Property::ImplicitLabels), - "explicit-labels" => Ok(Property::ExplicitLabels), - "state-acc" => Ok(Property::StateAcceptance), - "trans-acc" => Ok(Property::TransitionAcceptance), - "univ-branch" => Ok(Property::UniversalBranching), - "no-univ-branch" => Ok(Property::NoUniversalBranching), - "deterministic" => Ok(Property::Deterministic), - "complete" => Ok(Property::Complete), - "unambiguous" => Ok(Property::Unambiguous), - "stutter-invariant" => Ok(Property::StutterInvariant), - "weak" => Ok(Property::Weak), - "very-weak" => Ok(Property::VeryWeak), - "inherently-weak" => Ok(Property::InherentlyWeak), - "terminal" => Ok(Property::Terminal), - "tight" => Ok(Property::Tight), - "colored" => Ok(Property::Colored), - unknown => Err(format!("{} is not a valid property", unknown)), + "state-labels" => Property::StateLabels, + "trans-labels" => Property::TransLabels, + "implicit-labels" => Property::ImplicitLabels, + "explicit-labels" => Property::ExplicitLabels, + "state-acc" => Property::StateAcceptance, + "trans-acc" => Property::TransitionAcceptance, + "univ-branch" => Property::UniversalBranching, + "no-univ-branch" => Property::NoUniversalBranching, + "deterministic" => Property::Deterministic, + "complete" => Property::Complete, + "unambiguous" => Property::Unambiguous, + "stutter-invariant" => Property::StutterInvariant, + "weak" => Property::Weak, + "very-weak" => Property::VeryWeak, + "inherently-weak" => Property::InherentlyWeak, + "terminal" => Property::Terminal, + "tight" => Property::Tight, + "colored" => Property::Colored, + _ => Property::Other(value), } } } @@ -317,8 +317,8 @@ mod tests { fn terminal_property_is_parsed() { // the spelling "terminal" is the one that the writer produces assert_eq!( - super::Property::try_from("terminal".to_string()), - Ok(super::Property::Terminal) + super::Property::from("terminal".to_string()), + super::Property::Terminal ); } diff --git a/src/header.rs b/src/header.rs index 1ba6811..6d4043c 100644 --- a/src/header.rs +++ b/src/header.rs @@ -92,9 +92,7 @@ fn item() -> impl Parser> { let acceptance_name = just(Token::Header("acc-name".to_string())) .ignore_then(value::identifier()) - .try_map(|identifier, span| { - AcceptanceName::try_from(identifier).map_err(|e| Simple::custom(span, e)) - }) + .map(AcceptanceName::from) .then(value::acceptance_info().repeated()) .map(|(name, info)| HeaderItem::AcceptanceName(name, info)); @@ -138,7 +136,7 @@ fn item() -> impl Parser> { let properties = just(Token::Header("properties".to_string())) .ignore_then( value::identifier() - .try_map(|p, span| Property::try_from(p).map_err(|err| Simple::custom(span, err))) + .map(Property::from) .repeated() .at_least(1), ) @@ -318,7 +316,26 @@ mod tests { HeaderItem::Properties(vec![Property::TransLabels, Property::StateLabels]), ], ); - assert_fails(r#"properties: trans-labels statelabels"#); + assert_header( + "properties: trans-labels semi-deterministic", + &[ + HeaderItem::Version("v1".into()), + HeaderItem::Properties(vec![ + Property::TransLabels, + Property::Other("semi-deterministic".into()), + ]), + ], + ); + assert_header( + "acc-name: Rabin-like 1", + &[ + HeaderItem::Version("v1".into()), + HeaderItem::AcceptanceName( + AcceptanceName::Other("Rabin-like".into()), + vec![AcceptanceInfo::Int(1)], + ), + ], + ); assert_fails(r#"properties: "#); } diff --git a/src/output.rs b/src/output.rs index 4dba33c..84b5597 100644 --- a/src/output.rs +++ b/src/output.rs @@ -111,6 +111,7 @@ impl Display for Property { f, "{}", match self { + Property::Other(other) => other, Property::StateLabels => "state-labels", Property::TransLabels => "trans-labels", Property::ImplicitLabels => "implicit-labels", @@ -140,6 +141,7 @@ impl Display for AcceptanceName { f, "{}", match self { + AcceptanceName::Other(other) => other, AcceptanceName::Buchi => "Buchi", AcceptanceName::GeneralizedBuchi => "generalized-Buchi", AcceptanceName::CoBuchi => "co-Buchi", From 7cf4f88bd363e85af39e658d09e8774792d3aefc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Le=C3=B3n=20Bohn?= Date: Thu, 5 Nov 2026 13:46:32 +0100 Subject: [PATCH 3/6] Support alias references in labels and add unalias --- CHANGELOG.md | 1 + src/header.rs | 106 +++++++++++++++++--------------------------------- src/label.rs | 38 ++++++++++++++++++ src/lib.rs | 103 +++++++++++++++++++++++++++++++++++++++++++++++- src/value.rs | 4 +- 5 files changed, 179 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1cc796..0625b83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added +- Alias references (`@name`) in label expressions: `AbstractLabelExpression::Alias(String)`. `HoaRepresentation::unalias` substitutes them recursively in the aliases and in all edge labels and reports undefined or cyclic aliases. Parsing does not unalias; BDD conversion of an unresolved alias returns an error. - `HeaderItem::Unknown(name, values)` (with `UnknownValue`): unknown header items such as `controllable-AP:` or `spot.state-player:` are now parsed, kept, and written back out instead of being a parse error. Unknown names starting with an uppercase letter log a `tracing` warning. Header names may now contain `.`. ### Changed diff --git a/src/header.rs b/src/header.rs index 6d4043c..89be445 100644 --- a/src/header.rs +++ b/src/header.rs @@ -429,74 +429,40 @@ mod tests { ) } - // #[test] - // fn alias() { - // assert_header( - // "Alias: @a 0", - // &[ - // HeaderItem::Version("v1".to_string()), - // HeaderItem::Alias(AliasName("a".to_string()), LabelExpression::Integer(0)), - // ], - // ); - // assert_header( - // "Alias: @a 0 & 1", - // &[ - // HeaderItem::Version("v1".to_string()), - // HeaderItem::Alias( - // AliasName("a".to_string()), - // LabelExpression::And( - // Box::new(LabelExpression::Integer(0)), - // Box::new(LabelExpression::Integer(1)), - // ), - // ), - // ], - // ); - - // // & binds stronger - // assert_header( - // "Alias: @a 1 | 2 & 0", - // &[ - // HeaderItem::Version("v1".to_string()), - // HeaderItem::Alias( - // AliasName("a".to_string()), - // LabelExpression::Or( - // Box::new(LabelExpression::Integer(1)), - // Box::new(LabelExpression::And( - // Box::new(LabelExpression::Integer(2)), - // Box::new(LabelExpression::Integer(0)), - // )), - // ), - // ), - // ], - // ); - // assert_header( - // "Alias: @a 0 & 1 | 2", - // &[ - // HeaderItem::Version("v1".to_string()), - // HeaderItem::Alias( - // AliasName("a".to_string()), - // LabelExpression::Or( - // Box::new(LabelExpression::And( - // Box::new(LabelExpression::Integer(0)), - // Box::new(LabelExpression::Integer(1)), - // )), - // Box::new(LabelExpression::Integer(2)), - // ), - // ), - // ], - // ); - - // assert_header( - // "Alias: @a (0 | 1) & 2", - // &[ - // HeaderItem::Version("v1".to_string()), - // HeaderItem::Alias( - // AliasName("a".to_string()), - // Label, - // ), - // ], - // ); - // } - // #[test] - // fn multiple_headers() {} + #[test] + fn alias() { + use AbstractLabelExpression::*; + let alias = |x| HeaderItem::Alias(AliasName("a".to_string()), x); + let v1 = HeaderItem::Version("v1".to_string()); + assert_header("Alias: @a 0", &[v1.clone(), alias(Integer(0))]); + assert_header( + "Alias: @a 0 & 1", + &[v1.clone(), alias(Conjunction(vec![Integer(0), Integer(1)]))], + ); + // & binds stronger + assert_header( + "Alias: @a 1 | 2 & 0", + &[ + v1.clone(), + alias(Disjunction(vec![ + Integer(1), + Conjunction(vec![Integer(2), Integer(0)]), + ])), + ], + ); + assert_header( + "Alias: @a (0 | 1) & 2", + &[ + v1.clone(), + alias(Conjunction(vec![ + Disjunction(vec![Integer(0), Integer(1)]), + Integer(2), + ])), + ], + ); + assert_header( + "Alias: @a !@b", + &[v1, alias(Negated(Box::new(Alias("b".to_string()))))], + ); + } } diff --git a/src/label.rs b/src/label.rs index 2b35bc4..af24a75 100644 --- a/src/label.rs +++ b/src/label.rs @@ -17,6 +17,9 @@ impl Deref for Label { pub enum AbstractLabelExpression { Boolean(bool), Integer(u16), + /// A reference to an alias (`@name`, stored without the `@`); see + /// [`crate::HoaRepresentation::unalias`]. + Alias(String), Negated(Box), Conjunction(Vec), Disjunction(Vec), @@ -40,6 +43,9 @@ impl AbstractLabelExpression { Err(format!("AP identifier {i} is too high")) } } + AbstractLabelExpression::Alias(name) => Err(format!( + "alias @{name} is not resolved, call `HoaRepresentation::unalias` first" + )), AbstractLabelExpression::Negated(e) => Ok(e.try_into_bdd(vs)?.not()), AbstractLabelExpression::Conjunction(cs) => cs .iter() @@ -50,6 +56,38 @@ impl AbstractLabelExpression { } } + /// Replaces every alias reference by its (recursively substituted) definition. + /// `stack` holds the aliases currently being expanded and is used to detect cycles. + pub(crate) fn substitute( + &self, + defs: &std::collections::HashMap, + stack: &mut Vec, + ) -> Result { + let many = |es: &[Self], stack: &mut Vec| { + es.iter() + .map(|e| e.substitute(defs, stack)) + .collect::, _>>() + }; + Ok(match self { + Self::Alias(name) => { + if stack.contains(name) { + return Err(format!("alias @{name} is defined in terms of itself")); + } + let def = defs + .get(name) + .ok_or(format!("alias @{name} is not defined"))?; + stack.push(name.clone()); + let out = def.substitute(defs, stack); + stack.pop(); + out? + } + Self::Negated(e) => Self::Negated(Box::new(e.substitute(defs, stack)?)), + Self::Conjunction(es) => Self::Conjunction(many(es, stack)?), + Self::Disjunction(es) => Self::Disjunction(many(es, stack)?), + Self::Boolean(_) | Self::Integer(_) => self.clone(), + }) + } + /// Converts this expression into a [`Bdd`] over `num_aps` anonymous variables. pub fn try_into_prop(&self, num_aps: u16) -> Result { let var_set = BddVariableSet::new_anonymous(num_aps); diff --git a/src/lib.rs b/src/lib.rs index 8fb2716..10d43b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -234,6 +234,43 @@ impl HoaRepresentation { .collect() } + /// Replaces all alias references (`@name`) in the aliases and in the edge labels by + /// their definitions. The `Alias:` header items are kept. Fails on undefined or + /// cyclic aliases; on error the automaton is left unchanged. + /// + /// Parsing does not unalias, so call this before converting labels to BDDs. + pub fn unalias(&mut self) -> Result<(), String> { + let raw: std::collections::HashMap<_, _> = self + .aliases() + .into_iter() + .map(|(name, expr)| (name.0, expr)) + .collect(); + let defs = raw + .iter() + .map(|(name, expr)| { + Ok(( + name.clone(), + expr.substitute(&raw, &mut vec![name.clone()])?, + )) + }) + .collect::, String>>()?; + let mut body = self.body.clone(); + for edge in body.iter_mut().flat_map(|s| s.edges_mut()) { + if let LabelExpression::Abstract(expr) = &edge.label().0 { + edge.0 = Label(LabelExpression::Abstract( + expr.substitute(&defs, &mut vec![])?, + )); + } + } + for item in self.header.iter_mut() { + if let HeaderItem::Alias(name, expr) = item { + *expr = defs[&name.0].clone(); + } + } + self.body = body; + Ok(()) + } + /// Returns the acceptance name of the automaton, if the header has one. pub fn acceptance_name(&self) -> Option<(&AcceptanceName, &Vec)> { self.header().iter().find_map(|item| match item { @@ -273,6 +310,7 @@ impl std::fmt::Display for AbstractLabelExpression { false => write!(f, "f"), }, AbstractLabelExpression::Integer(i) => write!(f, "{i}"), + AbstractLabelExpression::Alias(name) => write!(f, "@{name}"), AbstractLabelExpression::Negated(expr) => { if is_atom(expr) { write!(f, "!{}", expr) @@ -310,7 +348,9 @@ impl std::fmt::Display for AbstractLabelExpression { fn is_atom(expr: &AbstractLabelExpression) -> bool { matches!( expr, - AbstractLabelExpression::Boolean(_) | AbstractLabelExpression::Integer(_) + AbstractLabelExpression::Boolean(_) + | AbstractLabelExpression::Integer(_) + | AbstractLabelExpression::Alias(_) ) } @@ -445,6 +485,67 @@ mod tests { label::AnonymousAbstract, }; + const ALIASED: &str = "HOA: v1 +States: 1 +Start: 0 +AP: 2 \"a\" \"b\" +Alias: @x 0 & 1 +Alias: @y !@x | 0 +Acceptance: 1 Inf(0) +--BODY-- +State: 0 +[@y] 0 {0} +[@x & !0] 0 +--END--"; + + #[test] + fn aliases_in_edges_and_aliases_unalias_convert_and_round_trip() { + let mut aut = HoaRepresentation::try_from(ALIASED).unwrap(); + let printed = crate::output::to_hoa(&aut); + assert_eq!(HoaRepresentation::try_from(printed.as_str()).unwrap(), aut); + assert!(printed.contains("[@y] 0"), "{printed}"); + + let before = aut.clone(); + aut.unalias().unwrap(); + let printed = crate::output::to_hoa(&aut); + assert!(printed.contains("Alias: @y !(0 & 1) | 0"), "{printed}"); + assert!(printed.contains("[!(0 & 1) | 0] 0 {0}"), "{printed}"); + // printing flattens nested conjunctions, so compare the labels as BDDs + let reparsed = HoaRepresentation::try_from(printed.as_str()).unwrap(); + let vs = biodivine_lib_bdd::BddVariableSet::new_anonymous(2); + let bdds = |a: &HoaRepresentation| { + a.body()[0] + .edges() + .iter() + .map(|e| { + let crate::LabelExpression::Abstract(l) = &e.label().0 else { + panic!() + }; + l.try_into_bdd(&vs).unwrap() + }) + .collect::>() + }; + assert_eq!(bdds(&aut), bdds(&reparsed)); + // unresolved aliases do not convert + let crate::LabelExpression::Abstract(l) = &before.body()[0].edges()[0].label().0 else { + panic!() + }; + assert!(l.try_into_bdd(&vs).is_err()); + } + + #[test] + fn unalias_rejects_undefined_and_cyclic_aliases() { + let undefined = ALIASED.replace("[@x & !0]", "[@z]"); + let mut aut = HoaRepresentation::try_from(undefined.as_str()).unwrap(); + let before = aut.clone(); + assert!(aut.unalias().unwrap_err().contains("@z is not defined")); + assert_eq!(aut, before); + + let cyclic = ALIASED.replace("Alias: @x 0 & 1", "Alias: @x @y"); + let mut aut = HoaRepresentation::try_from(cyclic.as_str()).unwrap(); + assert!(aut.unalias().unwrap_err().contains("itself")); + } + #[test] fn integer_overflow_is_a_parse_error() { let contents = "HOA: v1\nStates: 99999999999\n--BODY--\n--END--"; diff --git a/src/value.rs b/src/value.rs index 49b58ce..e2315eb 100644 --- a/src/value.rs +++ b/src/value.rs @@ -84,8 +84,8 @@ pub fn label_expression() -> impl Parser Date: Thu, 5 Nov 2026 13:47:30 +0100 Subject: [PATCH 4/6] Support implicit edge labels and state labels --- CHANGELOG.md | 1 + src/body.rs | 159 ++++++++++++++++++++++++++++++++------------------- src/lib.rs | 66 +++++++++++++++++++-- 3 files changed, 162 insertions(+), 64 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0625b83..4dce699 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added +- Implicit edge labels and state labels. A state without label whose edges have none needs exactly `2^|AP|` edges (edge `i` gets the label where AP `j` holds iff bit `j` of `i` is set); a state label is copied onto each of its outgoing edges; mixing labelled and unlabelled edges is a parse error. Implicit and state-labelled automata parse to the same `HoaRepresentation` as their explicit equivalents. - Alias references (`@name`) in label expressions: `AbstractLabelExpression::Alias(String)`. `HoaRepresentation::unalias` substitutes them recursively in the aliases and in all edge labels and reports undefined or cyclic aliases. Parsing does not unalias; BDD conversion of an unresolved alias returns an error. - `HeaderItem::Unknown(name, values)` (with `UnknownValue`): unknown header items such as `controllable-AP:` or `spot.state-player:` are now parsed, kept, and written back out instead of being a parse error. Unknown names starting with an uppercase letter log a `tracing` warning. Header names may now contain `.`. diff --git a/src/body.rs b/src/body.rs index cd3e82f..140dd5d 100644 --- a/src/body.rs +++ b/src/body.rs @@ -3,27 +3,27 @@ use std::ops::{Deref, DerefMut}; use chumsky::prelude::*; use crate::{ - AcceptanceSignature, AtomicProposition, Id, Label, LabelExpression, StateConjunction, - lexer::Token, value, + AbstractLabelExpression, AcceptanceSignature, AtomicProposition, Id, Label, LabelExpression, + StateConjunction, lexer::Token, value, }; #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[allow(unused)] pub struct Alphabet(pub Vec); +/// A state as parsed, before implicit labels and state labels are resolved. #[derive(Clone, Debug)] -pub struct RawState( - Option