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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),

## [Unreleased]

### Added

- `HoaRepresentation::validate`, run by the parser, with the new `FromHoaError::Invalid(ValidationError)`. It rejects a missing `Acceptance:`, repeated `States:`/`AP:`/`acc-name:`/`tool:`/`name:`/`Acceptance:` items, and acceptance sets, states and APs beyond the declared counts. Unsupported versions now give `FromHoaError::UnsupportedVersion`; `v1` and `v1.x` are accepted (the lexer accepts dotted versions such as `v1.1`).
- 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 `.`.

### Changed

- Lexer: strings follow the spec's C-like syntax (`\"` and `\\` are decoded, other escapes are kept verbatim), comments nest, and `--ABORT--` lexes as `Token::Abort` (it used to be `Token::BodyEnd`). `Token::Bool` is gone; `t`/`f` are identifiers.
- `--ABORT--` handling works on tokens instead of substrings: `from_hoa` only rejects real aborts (not one inside a string, nor `foo--ABORT--`), and `parse_hoa_automata` and `first_automaton_split_position` lex the input once and split the token stream, so an automaton following an aborted one in the same chunk is returned. A lexer error now makes `parse_hoa_automata` return nothing, and `first_automaton_split_position` return `None`.
- `Property` and `AcceptanceName` gained an `Other(String)` variant, and their `TryFrom<String>` impls became infallible `From<String>`. 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<String>`) and is empty when the header has no `AP:`;
- `num_aps` returns `u16` (was `u8`, which panicked above 255 APs);
Expand Down
159 changes: 100 additions & 59 deletions src/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AtomicProposition>);

/// A state as parsed, before implicit labels and state labels are resolved.
#[derive(Clone, Debug)]
pub struct RawState(
Option<Label>,
Id,
Option<String>,
Option<AcceptanceSignature>,
);

#[derive(Clone, Debug, PartialEq, Eq)]
struct ExplicitEdge(Label, StateConjunction, Option<AcceptanceSignature>);
pub(crate) struct RawState {
label: Option<Label>,
id: Id,
comment: Option<String>,
acc: Option<AcceptanceSignature>,
edges: Vec<RawEdge>,
}

/// An edge as parsed; the label is missing for implicit-label edges and state-label states.
#[derive(Clone, Debug, PartialEq, Eq)]
struct ImplicitEdge(StateConjunction, Option<AcceptanceSignature>);
struct RawEdge(Option<Label>, StateConjunction, Option<AcceptanceSignature>);

/// Represents an edge in a HOA automaton. It contains the [`crate::LabelExpression`], the
/// [`StateConjunction`] and the [`AcceptanceSignature`] of the edge.
Expand Down Expand Up @@ -107,39 +107,82 @@ impl State {
}
}

impl From<(Option<AcceptanceSignature>, ExplicitEdge)> for Edge {
fn from((state_acc, edge): (Option<AcceptanceSignature>, ExplicitEdge)) -> Self {
let acc = match (state_acc, &edge.2) {
(None, None) => AcceptanceSignature(Vec::new()),
(Some(acc), None) => acc,
(None, Some(acc)) => acc.clone(),
(Some(left), Some(right)) => {
AcceptanceSignature(left.iter().cloned().chain(right.iter().cloned()).collect())
}
};
Edge(edge.0, edge.1, acc)
}
}

impl TryFrom<(RawState, Vec<ExplicitEdge>)> for State {
type Error = String;

fn try_from((state, edges): (RawState, Vec<ExplicitEdge>)) -> Result<Self, Self::Error> {
let mut out_edges = vec![];
let RawState(state_label, id, state_text, state_acc) = state;

if state_label.is_some() {
return Err("Transformation from state-based to transition-based requires adding a new initial state etc (see example 'non-deterministic state-based Büchi Automaton')".to_string());
impl RawState {
/// Resolves implicit labels and the state label into explicit edge labels.
/// `num_aps` is the number of atomic propositions declared in the header.
///
/// - A labelled state must have unlabelled edges, each of which gets the state label.
/// - An unlabelled state with unlabelled edges must have exactly `2^num_aps` edges;
/// edge `i` gets the label in which AP `j` is true iff bit `j` of `i` is set.
/// - Mixing labelled and unlabelled edges is an error.
pub(crate) fn resolve(self, num_aps: u16) -> Result<State, String> {
let RawState {
label: state_label,
id,
comment,
acc: state_acc,
edges,
} = self;
let labelled = edges.iter().filter(|e| e.0.is_some()).count();
if state_label.is_some() && labelled > 0 {
return Err(format!(
"State {id} has a state label, so its edges must not have labels"
));
}

for raw_edge in edges {
out_edges.push(Edge::from((state_acc.clone(), raw_edge)));
if labelled > 0 && labelled < edges.len() {
return Err(format!("State {id} mixes labelled and unlabelled edges"));
}
let implicit = state_label.is_none() && labelled == 0 && !edges.is_empty();
if implicit && (num_aps >= 32 || edges.len() != 1usize << num_aps) {
return Err(format!(
"State {id} has implicit edge labels, so it needs exactly 2^{num_aps} edges but has {}",
edges.len()
));
}

Ok(State(id, state_text, out_edges))
let out_edges = edges
.into_iter()
.enumerate()
.map(|(i, RawEdge(label, conj, acc))| {
let label = match (label, &state_label) {
(Some(l), _) => l,
(None, Some(l)) => l.clone(),
(None, None) => implicit_label(i, num_aps),
};
let acc = match (&state_acc, acc) {
(None, None) => AcceptanceSignature(Vec::new()),
(Some(acc), None) => acc.clone(),
(None, Some(acc)) => acc,
(Some(left), Some(right)) => AcceptanceSignature(
left.iter().cloned().chain(right.iter().cloned()).collect(),
),
};
Edge(label, conj, acc)
})
.collect();
Ok(State(id, comment, out_edges))
}
}

/// The label of the `i`-th implicit edge: AP `j` is positive iff bit `j` of `i` is set.
fn implicit_label(i: usize, num_aps: u16) -> Label {
let mut literals: Vec<_> = (0..num_aps)
.map(|j| {
let ap = AbstractLabelExpression::Integer(j);
if i >> j & 1 == 1 {
ap
} else {
AbstractLabelExpression::Negated(Box::new(ap))
}
})
.collect();
Label(LabelExpression::Abstract(match literals.len() {
0 => AbstractLabelExpression::Boolean(true),
1 => literals.remove(0),
_ => AbstractLabelExpression::Conjunction(literals),
}))
}

pub fn label() -> impl Parser<Token, Label, Error = Simple<Token>> {
just(Token::Paren('['))
.ignore_then(value::label_expression())
Expand All @@ -148,37 +191,33 @@ pub fn label() -> impl Parser<Token, Label, Error = Simple<Token>> {
.map(Label)
}

fn explicit_edge() -> impl Parser<Token, ExplicitEdge, Error = Simple<Token>> {
fn edge() -> impl Parser<Token, RawEdge, Error = Simple<Token>> {
label()
.or_not()
.then(value::state_conjunction())
.then(value::acceptance_signature().or_not())
.map(|((label, state_conjunction), acceptance_signature)| {
ExplicitEdge(label, state_conjunction, acceptance_signature)
RawEdge(label, state_conjunction, acceptance_signature)
})
}

// For now, we allow only explicit edges, but this might change in the future. In any case, we already have the necessary
// infrastructure to support implicit edges.
#[allow(unused)]
fn implicit_edge() -> impl Parser<Token, ImplicitEdge, Error = Simple<Token>> {
value::state_conjunction()
.then(value::acceptance_signature().or_not())
.map(|(label, acceptance_signature)| ImplicitEdge(label, acceptance_signature))
}

#[allow(clippy::result_large_err)]
pub fn state() -> impl Parser<Token, State, Error = Simple<Token>> {
pub(crate) fn state() -> impl Parser<Token, RawState, Error = Simple<Token>> {
just(Token::Header("State".to_string()))
.ignore_then(
label()
.or_not()
.then(value::integer())
.then(value::text().or_not())
.then(value::acceptance_signature().or_not())
.map(|(((l, i), t), a)| RawState(l, i, t, a)),
.then(value::acceptance_signature().or_not()),
)
.then(explicit_edge().repeated())
.try_map(|input, span| State::try_from(input).map_err(|err| Simple::custom(span, err)))
.then(edge().repeated())
.map(|((((label, id), comment), acc), edges)| RawState {
label,
id,
comment,
acc,
edges,
})
}

/// Represents the body of a HOA automaton. In essence, this is just a vector of [`State`]s.
Expand All @@ -201,10 +240,9 @@ impl Body {
Self(Vec::new())
}

pub(crate) fn parser() -> impl Parser<Token, Self, Error = Simple<Token>> {
pub(crate) fn parser() -> impl Parser<Token, Vec<RawState>, Error = Simple<Token>> {
just(Token::BodyStart)
.ignore_then(state().repeated())
.map(Body)
.then_ignore(just(Token::BodyEnd))
}
}
Expand Down Expand Up @@ -267,7 +305,10 @@ mod tests {
error_list.into_iter().map(|err| err.map(|c| c.to_string())),
)
})?;
Ok(ast.0)
// the tests only use explicit labels, so the AP count does not matter
ast.into_iter()
.map(|s| s.resolve(0).map_err(|_| ()))
.collect()
}

#[test]
Expand Down
95 changes: 55 additions & 40 deletions src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,21 @@ pub enum AcceptanceCondition {
}

impl AcceptanceCondition {
/// All acceptance sets mentioned in this condition.
pub(crate) fn sets(&self) -> Vec<Id> {
match self {
Self::Fin(a) | Self::Inf(a) => match a {
AcceptanceAtom::Positive(i) | AcceptanceAtom::Negative(i) => vec![*i],
},
Self::And(l, r) | Self::Or(l, r) => {
let mut sets = l.sets();
sets.extend(r.sets());
sets
}
Self::Boolean(_) => Vec::new(),
}
}

fn parity_rec(current: u32, total: u32) -> Self {
if current + 1 >= total {
if current.rem(2) == 0 {
Expand Down Expand Up @@ -206,6 +221,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 {
Expand All @@ -214,22 +231,20 @@ impl AcceptanceName {
}
}

impl TryFrom<String> for AcceptanceName {
type Error = String;

fn try_from(value: String) -> Result<Self, Self::Error> {
impl From<String> 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),
}
}
}
Expand Down Expand Up @@ -257,32 +272,32 @@ pub enum Property {
Terminal,
Tight,
Colored,
/// Any other property (e.g. Spot's `semi-deterministic`), kept verbatim.
Other(String),
}

impl TryFrom<String> for Property {
type Error = String;

fn try_from(value: String) -> Result<Self, Self::Error> {
impl From<String> 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),
}
}
}
Expand Down Expand Up @@ -317,8 +332,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
);
}

Expand Down
Loading
Loading