diff --git a/CHANGELOG.md b/CHANGELOG.md index fd4dd21..5ad549b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Changed + +- **Breaking:** label conversion returns the new `LabelError` instead of a `String`: `AbstractLabelExpression::try_into_bdd`, `AbstractLabelExpression::try_into_prop` and `LabelExpression::try_into_hoa_expression`. It tells an out-of-range AP (`LabelError::ApOutOfRange { ap, count }`) from an unresolved alias (`LabelError::UnresolvedAlias(name)`) and implements `std::error::Error` (issue 6). +- **Breaking:** `HoaRepresentation::unalias` returns the new `AliasError` (`Undefined`, `Cyclic`) and `HoaRepresentation::verify` returns `VerifyErrors`, a list of `VerifyError` (`DuplicateState`, `StateCountMismatch`), instead of `String`. Both implement `std::error::Error`, and `VerifyErrors` derefs to `[VerifyError]` (issue 6). + ## [0.4.0] - 2026-11-06 ### Added diff --git a/src/error.rs b/src/error.rs index dade4b2..81f471f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -137,6 +137,115 @@ impl Display for ValidationError { } } +/// Why a label expression could not be converted to a BDD, see +/// [`crate::AbstractLabelExpression::try_into_bdd`]. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum LabelError { + /// The expression uses an atomic proposition that the variable set does not have. + ApOutOfRange { + /// The offending atomic proposition. + ap: u16, + /// The number of variables in the BDD variable set. + count: u16, + }, + /// The expression contains an alias reference (`@name`) that was not substituted; + /// call [`crate::HoaRepresentation::unalias`] before converting. + UnresolvedAlias(String), +} + +impl Display for LabelError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::ApOutOfRange { ap, count } => { + write!( + f, + "AP identifier {ap} is too high, the set has {count} variables" + ) + } + Self::UnresolvedAlias(name) => write!( + f, + "alias @{name} is not resolved, call `HoaRepresentation::unalias` first" + ), + } + } +} + +impl std::error::Error for LabelError {} + +/// An `@name` reference that [`crate::HoaRepresentation::unalias`] cannot substitute. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum AliasError { + /// There is no `Alias:` item for this name. + Undefined(String), + /// The name is part of a cycle, i.e. it is defined in terms of itself. + Cyclic(String), +} + +impl Display for AliasError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Undefined(name) => write!(f, "alias @{name} is not defined"), + Self::Cyclic(name) => write!(f, "alias @{name} is defined in terms of itself"), + } + } +} + +impl std::error::Error for AliasError {} + +/// A violation found by [`crate::HoaRepresentation::verify`]. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum VerifyError { + /// The body defines this state more than once. + DuplicateState(Id), + /// `States:` disagrees with the number of states in the body. + StateCountMismatch { + /// The number stated in the header. + declared: usize, + /// The number of states in the body. + actual: usize, + }, +} + +impl Display for VerifyError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::DuplicateState(state) => write!(f, "state {state} is defined more than once"), + Self::StateCountMismatch { declared, actual } => { + write!(f, "`States:` says {declared} but the body defines {actual}") + } + } + } +} + +impl std::error::Error for VerifyError {} + +/// All violations found by [`crate::HoaRepresentation::verify`], in the order found. +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct VerifyErrors(Vec); + +impl VerifyErrors { + pub(crate) fn new(errors: Vec) -> Self { + Self(errors) + } +} + +impl std::ops::Deref for VerifyErrors { + type Target = [VerifyError]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for VerifyErrors { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let messages: Vec<_> = self.0.iter().map(ToString::to_string).collect(); + write!(f, "{}", messages.join("; ")) + } +} + +impl std::error::Error for VerifyErrors {} + impl Display for FromHoaError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { @@ -209,4 +318,31 @@ mod tests { (|| Ok(HoaRepresentation::try_from(src)?))(); assert!(boxed.is_err()); } + + #[test] + fn conversion_errors_are_std_errors() { + let boxed = |e: Box| e.to_string(); + assert!( + boxed(Box::new(crate::LabelError::ApOutOfRange { + ap: 2, + count: 1 + })) + .contains("AP identifier 2") + ); + assert!( + boxed(Box::new(crate::AliasError::Undefined("a".into()))).contains("@a is not defined") + ); + assert!(boxed(Box::new(crate::VerifyError::DuplicateState(1))).contains("state 1")); + let errors = crate::VerifyErrors::new(vec![ + crate::VerifyError::DuplicateState(1), + crate::VerifyError::StateCountMismatch { + declared: 2, + actual: 1, + }, + ]); + assert_eq!( + boxed(Box::new(errors)).as_str(), + "state 1 is defined more than once; `States:` says 2 but the body defines 1" + ); + } } diff --git a/src/label.rs b/src/label.rs index 294c539..2a44752 100644 --- a/src/label.rs +++ b/src/label.rs @@ -1,6 +1,8 @@ use biodivine_lib_bdd::{Bdd, BddVariable, BddVariableSet}; use std::ops::Deref; +use crate::{AliasError, LabelError}; + /// Newtype wrapper around a [`crate::LabelExpression`], implements [`Deref`]. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Label(pub LabelExpression); @@ -36,7 +38,7 @@ impl AbstractLabelExpression { /// /// The variable for AP `i` is `BddVariable::from_index(i)`, so `vs` must have at /// least as many variables as the largest AP identifier used in this expression. - pub fn try_into_bdd(&self, vs: &BddVariableSet) -> Result { + pub fn try_into_bdd(&self, vs: &BddVariableSet) -> Result { match self { AbstractLabelExpression::Boolean(b) => Ok(match b { true => vs.mk_true(), @@ -46,12 +48,13 @@ impl AbstractLabelExpression { if *i < vs.num_vars() { Ok(vs.mk_var(BddVariable::from_index(*i as usize))) } else { - Err(format!("AP identifier {i} is too high")) + Err(LabelError::ApOutOfRange { + ap: *i, + count: vs.num_vars(), + }) } } - AbstractLabelExpression::Alias(name) => Err(format!( - "alias @{name} is not resolved, call `HoaRepresentation::unalias` first" - )), + AbstractLabelExpression::Alias(name) => Err(LabelError::UnresolvedAlias(name.clone())), AbstractLabelExpression::Negated(e) => Ok(e.try_into_bdd(vs)?.not()), AbstractLabelExpression::Conjunction(cs) => cs .iter() @@ -80,7 +83,7 @@ impl AbstractLabelExpression { &self, defs: &std::collections::HashMap, stack: &mut Vec, - ) -> Result { + ) -> Result { let many = |es: &[Self], stack: &mut Vec| { es.iter() .map(|e| e.substitute(defs, stack)) @@ -89,11 +92,9 @@ impl AbstractLabelExpression { Ok(match self { Self::Alias(name) => { if stack.contains(name) { - return Err(format!("alias @{name} is defined in terms of itself")); + return Err(AliasError::Cyclic(name.clone())); } - let def = defs - .get(name) - .ok_or(format!("alias @{name} is not defined"))?; + let def = defs.get(name).ok_or(AliasError::Undefined(name.clone()))?; stack.push(name.clone()); let out = def.substitute(defs, stack); stack.pop(); @@ -107,7 +108,7 @@ impl AbstractLabelExpression { } /// Converts this expression into a [`Bdd`] over `num_aps` anonymous variables. - pub fn try_into_prop(&self, num_aps: u16) -> Result { + pub fn try_into_prop(&self, num_aps: u16) -> Result { let var_set = BddVariableSet::new_anonymous(num_aps); self.try_into_bdd(&var_set) } @@ -134,7 +135,7 @@ pub enum LabelExpression { impl LabelExpression { /// Converts the expression into a BDD over `num_aps` variables. - pub fn try_into_hoa_expression(self, num_aps: u16) -> Result { + pub fn try_into_hoa_expression(self, num_aps: u16) -> Result { match self { LabelExpression::Expression(b) => Ok(b), LabelExpression::Abstract(b) => b.try_into_prop(num_aps), @@ -260,7 +261,25 @@ mod tests { #[test] fn out_of_bounds_ap_is_an_error() { let expr = Conjunction(vec![Integer(0), not(int(7))]); - assert!(expr.try_into_prop(2).is_err()); - assert!(Integer(7).try_into_prop(2).is_err()); + let expected = LabelError::ApOutOfRange { ap: 7, count: 2 }; + assert_eq!(expr.try_into_prop(2), Err(expected.clone())); + assert_eq!(Integer(7).try_into_prop(2), Err(expected.clone())); + assert_eq!( + LabelExpression::Abstract(Integer(7)).try_into_hoa_expression(2), + Err(expected) + ); + } + + #[test] + fn unresolved_alias_is_an_error() { + let expr = AbstractLabelExpression::Alias("x".into()); + assert_eq!( + expr.try_into_prop(2), + Err(LabelError::UnresolvedAlias("x".into())) + ); + assert_eq!( + expr.try_into_prop(2).unwrap_err().to_string(), + "alias @x is not resolved, call `HoaRepresentation::unalias` first" + ); } } diff --git a/src/lib.rs b/src/lib.rs index 1336e42..9aec4f4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,7 +26,9 @@ use chumsky::{Parser, prelude::end}; pub use format::*; pub use body::{Body, Edge, State}; -pub use error::{Diagnostic, FromHoaError, ValidationError}; +pub use error::{ + AliasError, Diagnostic, FromHoaError, LabelError, ValidationError, VerifyError, VerifyErrors, +}; pub use header::{Header, HeaderItem, UnknownValue}; use itertools::Itertools; @@ -116,29 +118,28 @@ impl HoaRepresentation { /// Verifies that the automaton is well-formed. This means that /// - the number of states is set correctly /// - all states are defined exactly once - pub fn verify(&self) -> Result<(), String> { + pub fn verify(&self) -> Result<(), VerifyErrors> { + use VerifyError::*; let mut errors = Vec::new(); // `body_mut`/`add_state` can leave the body unsorted, so sort the ids instead of relying on it let mut states: Vec<_> = self.body().iter().map(|s| s.id()).collect(); states.sort_unstable(); for pair in states.windows(2) { if pair[0] == pair[1] { - errors.push(format!("State {} is defined more than once!", pair[0])); + errors.push(DuplicateState(pair[0])); } } if let Some(num_states) = self.num_states() && states.len() != num_states { - errors.push(format!( - "The number of states is set to {} but there are {} states!", - num_states, - states.len() - )); + errors.push(StateCountMismatch { + declared: num_states, + actual: states.len(), + }); } - if errors.is_empty() { - Ok(()) - } else { - Err(errors.join("\n")) + match errors.is_empty() { + true => Ok(()), + false => Err(VerifyErrors::new(errors)), } } @@ -266,20 +267,21 @@ impl HoaRepresentation { /// 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> { + pub fn unalias(&mut self) -> Result<(), AliasError> { let raw: std::collections::HashMap<_, _> = self .alias_iter() .map(|(name, expr)| (name.0.clone(), expr.clone())) .collect(); - let defs = raw - .iter() + // walk the aliases in file order so that a reported cycle does not depend on map order + let defs = self + .alias_iter() .map(|(name, expr)| { Ok(( - name.clone(), - expr.substitute(&raw, &mut vec![name.clone()])?, + name.0.clone(), + expr.substitute(&raw, &mut vec![name.0.clone()])?, )) }) - .collect::, String>>()?; + .collect::, AliasError>>()?; 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 { @@ -498,7 +500,10 @@ State: 0 let crate::LabelExpression::Abstract(l) = &before.body()[0].edges()[0].label().0 else { panic!() }; - assert!(l.try_into_bdd(&vs).is_err()); + assert_eq!( + l.try_into_bdd(&vs), + Err(crate::LabelError::UnresolvedAlias("y".into())) + ); } #[test] @@ -506,12 +511,19 @@ State: 0 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.unalias().unwrap_err(), + crate::AliasError::Undefined("z".into()) + ); 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")); + // the first alias in file order closes the cycle + assert_eq!( + aut.unalias().unwrap_err(), + crate::AliasError::Cyclic("x".into()) + ); } fn with_body(body: &str) -> String { @@ -820,7 +832,26 @@ State: 0 aut.add_state(dup); assert!(aut.body().windows(2).all(|w| w[0].id() <= w[1].id())); let err = aut.verify().unwrap_err(); - assert!(err.contains("State 0 is defined more than once!"), "{err}"); + assert_eq!( + err.to_string(), + "state 0 is defined more than once; `States:` says 3 but the body defines 4" + ); + assert_eq!(err[0], crate::VerifyError::DuplicateState(0)); + } + + #[test] + fn verify_reports_state_count_mismatch() { + let aut = HoaRepresentation::try_from( + "HOA: v1\nStates: 3\nAcceptance: 0 t\n--BODY--\nState: 0\n--END--", + ) + .unwrap(); + assert_eq!( + aut.verify().unwrap_err().to_vec(), + vec![crate::VerifyError::StateCountMismatch { + declared: 3, + actual: 1 + }] + ); } /// Every file in `hoa/` (not the benchmarks) parses, round-trips and converts to BDDs.