use crate::document::{Document, State, StateKind, Transition};
use std::collections::HashMap;
pub(super) struct Context<'d> {
pub(super) source: &'d str,
pub(super) states: Vec<&'d State>,
parents: Vec<Option<usize>>,
by_id: HashMap<&'d str, usize>,
pub(super) transitions: Vec<&'d Transition>,
pub(super) invoke_content_markup: bool,
}
impl<'d> Context<'d> {
pub(super) fn build(
document: &'d Document,
source: &'d str,
invoke_content_markup: bool,
) -> Self {
let mut context = Context {
source,
states: Vec::new(),
parents: Vec::new(),
by_id: HashMap::new(),
transitions: Vec::new(),
invoke_content_markup,
};
context.walk(&document.states, None);
for (index, state) in context.states.iter().enumerate() {
if let Some(id) = &state.id {
context.by_id.insert(id, index);
}
context.transitions.extend(&state.transitions);
if state.kind != StateKind::History {
if let Some(initial) = &state.initial_element {
context.transitions.extend(&initial.transitions);
}
}
}
context
}
fn walk(&mut self, children: &'d [State], parent: Option<usize>) {
for state in children {
let index = self.states.len();
self.states.push(state);
self.parents.push(parent);
self.walk(&state.states, Some(index));
}
}
pub(super) fn resolve(&self, id: &str) -> Option<usize> {
self.by_id.get(id).copied()
}
pub(super) fn parent(&self, index: usize) -> Option<usize> {
self.parents.get(index).copied().flatten()
}
pub(super) fn inside(&self, index: usize, ancestor: usize) -> bool {
let mut current = self.parent(index);
while let Some(parent) = current {
if parent == ancestor {
return true;
}
current = self.parent(parent);
}
false
}
}
pub(super) fn is_compound(state: &State) -> bool {
matches!(state.kind, StateKind::State | StateKind::Parallel) && !state.states.is_empty()
}
pub(super) fn kind_name(kind: StateKind) -> &'static str {
match kind {
StateKind::State => "state",
StateKind::Parallel => "parallel",
StateKind::Final => "final",
StateKind::History => "history",
}
}