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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
136 changes: 136 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<VerifyError>);

impl VerifyErrors {
pub(crate) fn new(errors: Vec<VerifyError>) -> 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 {
Expand Down Expand Up @@ -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<dyn std::error::Error>| 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"
);
}
}
47 changes: 33 additions & 14 deletions src/label.rs
Original file line number Diff line number Diff line change
@@ -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);
Expand Down Expand Up @@ -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<Bdd, String> {
pub fn try_into_bdd(&self, vs: &BddVariableSet) -> Result<Bdd, LabelError> {
match self {
AbstractLabelExpression::Boolean(b) => Ok(match b {
true => vs.mk_true(),
Expand All @@ -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()
Expand Down Expand Up @@ -80,7 +83,7 @@ impl AbstractLabelExpression {
&self,
defs: &std::collections::HashMap<String, AbstractLabelExpression>,
stack: &mut Vec<String>,
) -> Result<Self, String> {
) -> Result<Self, AliasError> {
let many = |es: &[Self], stack: &mut Vec<String>| {
es.iter()
.map(|e| e.substitute(defs, stack))
Expand All @@ -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();
Expand All @@ -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<HoaExpression, String> {
pub fn try_into_prop(&self, num_aps: u16) -> Result<HoaExpression, LabelError> {
let var_set = BddVariableSet::new_anonymous(num_aps);
self.try_into_bdd(&var_set)
}
Expand All @@ -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<HoaExpression, String> {
pub fn try_into_hoa_expression(self, num_aps: u16) -> Result<HoaExpression, LabelError> {
match self {
LabelExpression::Expression(b) => Ok(b),
LabelExpression::Abstract(b) => b.try_into_prop(num_aps),
Expand Down Expand Up @@ -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"
);
}
}
Loading
Loading