use std::collections::{HashMap, HashSet};
use crate::{
ast::{State, StateDiagram, StateStmt},
builder::ir::{
self,
common::{
ArrowKind, ArrowSpec, EdgePriority, LabelSpec, PortHint, PortSet, SizeHint, StyleRef,
},
shape::ShapeKind,
unigraph::{EdgeKind, UGEdge, UGNode, UGSubgraph, Unigraph},
},
};
use lievisual::geometry::Size;
type CompositeLinks = (Option<String>, Option<String>, Vec<String>);
const DEFAULT_DIRECTION: crate::ast::Direction = crate::ast::Direction::TB;
const START_SIZE: Size = Size::new(14.0, 14.0);
const END_SIZE: Size = Size::new(20.0, 20.0);
const BAR_SIZE: Size = Size::new(100.0, 10.0);
const STATE_PAD: f64 = 8.0;
fn node_meta(_id: &str, is_start: bool, is_end: bool, is_bar: bool) -> (ShapeKind, SizeHint) {
if is_start {
(ShapeKind::StartDot, SizeHint::Fixed(START_SIZE))
} else if is_end {
(ShapeKind::EndDot, SizeHint::Fixed(END_SIZE))
} else if is_bar {
(ShapeKind::Bar, SizeHint::Fixed(BAR_SIZE))
} else {
(
ShapeKind::Rounded,
SizeHint::Padded {
pad_x: STATE_PAD,
pad_y: STATE_PAD,
},
)
}
}
fn push_node(
nodes: &mut Vec<UGNode>,
seen: &mut HashSet<String>,
id: String,
label: Option<String>,
shape: ShapeKind,
size_hint: SizeHint,
) {
if seen.contains(&id) {
return;
}
seen.insert(id.clone());
let text = match shape {
ShapeKind::StartDot | ShapeKind::EndDot | ShapeKind::Bar => label.unwrap_or_default(),
_ => label.unwrap_or_else(|| id.clone()),
};
nodes.push(UGNode {
id,
kind: ir::common::NodeKind::Atom,
role: ir::common::NodeRole::Atom,
shape,
label: ir::common::LabelOrMeasured::Spec(LabelSpec {
text,
spans: Vec::new(),
}),
ports: PortSet::default(),
size_hint,
style_ref: StyleRef::NodeDefault,
constraint: ir::common::NodeConstraint::Free,
detail: ir::common::NodeDetail::None,
});
}
fn transition_seen_first(sd: &StateDiagram) -> HashSet<String> {
let mut out = HashSet::new();
let mut first_is_trans: HashSet<String> = HashSet::new();
for stmt in &sd.order {
match stmt {
StateStmt::Decl(i) => {
let Some(s) = sd.states.get(*i) else { continue };
let id = match s {
State::Simple { id, .. }
| State::Composite { id, .. }
| State::Fork { id }
| State::Join { id } => id.as_str(),
State::Start | State::End => continue,
};
if first_is_trans.contains(id) {
out.insert(id.to_string());
}
}
StateStmt::Trans(i) => {
let Some(t) = sd.transitions.get(*i) else {
continue;
};
for id in [&t.from, &t.to] {
if *id != "[*]" {
first_is_trans.insert(id.clone());
}
}
}
}
}
out
}
pub fn extract_state(sd: &StateDiagram) -> Unigraph {
let mut nodes: Vec<UGNode> = Vec::new();
let mut edges: Vec<UGEdge> = Vec::new();
let mut subgraphs: Vec<UGSubgraph> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
let mut edge_counter: usize = 0;
let mut labels: HashMap<String, Option<String>> = HashMap::new();
fn collect_labels(sd: &StateDiagram, labels: &mut HashMap<String, Option<String>>) {
for s in &sd.states {
match s {
State::Simple { id, description } => {
labels.insert(id.clone(), description.clone());
}
State::Composite { inner, .. } => collect_labels(inner, labels),
_ => {}
}
}
}
collect_labels(sd, &mut labels);
let mut composite_entry_exit: HashMap<String, CompositeLinks> = HashMap::new();
#[allow(clippy::too_many_arguments)]
fn collect(
sd: &StateDiagram,
nodes: &mut Vec<UGNode>,
edges: &mut Vec<UGEdge>,
subgraphs: &mut Vec<UGSubgraph>,
seen: &mut HashSet<String>,
labels: &HashMap<String, Option<String>>,
composite_entry_exit: &mut HashMap<String, CompositeLinks>,
edge_counter: &mut usize,
is_inner: bool,
degraded: &HashSet<String>,
container_id: Option<&str>,
) -> (Option<String>, Option<String>) {
let mut entry: Option<String> = None;
let mut exit: Option<String> = None;
let start_dot_id = || format!("__start__{}", container_id.unwrap_or("__root__"));
let end_dot_id = || format!("__end__{}", container_id.unwrap_or("__root__"));
let push_edge = |edges: &mut Vec<UGEdge>,
edge_counter: &mut usize,
from: String,
to: String,
label: Option<String>| {
edges.push(UGEdge {
id: format!("t{}", *edge_counter),
source: from,
target: to,
source_port: PortHint::Bottom,
target_port: PortHint::Top,
kind: EdgeKind::StateTransition,
label_text: label,
label: None,
priority: EdgePriority::Primary,
routing_hint: ir::common::RoutingHint::Spline,
arrow: ArrowSpec {
start: ArrowKind::None,
end: ArrowKind::Arrow,
},
line_kind: ir::common::LineKind::Solid,
repulsion: 1.0,
cardinality: (None, None),
cardinality_text: (None, None),
});
*edge_counter += 1;
};
for s in &sd.states {
match s {
State::Simple { id, .. } => {
let (shape, hint) = node_meta(id, false, false, false);
push_node(
nodes,
seen,
id.clone(),
labels.get(id).cloned().flatten(),
shape,
hint,
);
}
State::Composite { id, inner } => {
let start_idx = nodes.len();
let (e, x) = collect(
inner,
nodes,
edges,
subgraphs,
seen,
labels,
composite_entry_exit,
edge_counter,
true,
degraded,
Some(id.as_str()),
);
let member_ids: Vec<String> =
nodes[start_idx..].iter().map(|n| n.id.clone()).collect();
subgraphs.push(UGSubgraph {
id: id.clone(),
title: Some(id.clone()),
member_ids: member_ids.clone(),
direction: None,
kind: ir::common::ContainerKind::StateComposite,
});
composite_entry_exit.insert(id.clone(), (e.clone(), x.clone(), member_ids));
entry = e;
exit = x;
}
State::Fork { id } | State::Join { id } => {
if degraded.contains(id) {
let (shape, hint) = node_meta(id, false, false, false);
push_node(
nodes,
seen,
id.clone(),
labels.get(id).cloned().flatten(),
shape,
hint,
);
} else {
let (shape, hint) = node_meta(id, false, false, true);
push_node(nodes, seen, id.clone(), None, shape, hint);
}
}
State::Start => {
push_node(
nodes,
seen,
"__start__".to_string(),
None,
ShapeKind::StartDot,
SizeHint::Fixed(START_SIZE),
);
}
State::End => {
push_node(
nodes,
seen,
"__end__".to_string(),
None,
ShapeKind::EndDot,
SizeHint::Fixed(END_SIZE),
);
}
}
}
for t in &sd.transitions {
let from_is_star = t.from == "[*]";
let to_is_star = t.to == "[*]";
if is_inner && (from_is_star || to_is_star) {
let dot_from = from_is_star.then(|| {
let dot = start_dot_id();
push_node(
nodes,
seen,
dot.clone(),
None,
ShapeKind::StartDot,
SizeHint::Fixed(START_SIZE),
);
dot
});
let dot_to = to_is_star.then(|| {
let dot = end_dot_id();
push_node(
nodes,
seen,
dot.clone(),
None,
ShapeKind::EndDot,
SizeHint::Fixed(END_SIZE),
);
dot
});
let from = dot_from.unwrap_or_else(|| t.from.clone());
let to = dot_to.unwrap_or_else(|| t.to.clone());
let entry_dot = from_is_star.then(|| from.clone());
let exit_dot = to_is_star.then(|| to.clone());
if from != to {
if !from_is_star {
let (shape, hint) = node_meta(&from, false, false, false);
push_node(
nodes,
seen,
from.clone(),
labels.get(&from).cloned().flatten(),
shape,
hint,
);
}
if !to_is_star {
let (shape, hint) = node_meta(&to, false, false, false);
push_node(
nodes,
seen,
to.clone(),
labels.get(&to).cloned().flatten(),
shape,
hint,
);
}
push_edge(edges, edge_counter, from, to, t.label.clone());
}
if let Some(d) = entry_dot {
entry = Some(d);
}
if let Some(d) = exit_dot {
exit = Some(d);
}
continue;
}
let mut from = if from_is_star {
"__start__".to_string()
} else {
t.from.clone()
};
let mut to = if to_is_star {
"__end__".to_string()
} else {
t.to.clone()
};
if let Some((_, x, members)) = composite_entry_exit.get(&from)
&& let Some(x) = x.as_ref().or_else(|| members.last())
{
from = x.clone();
}
if let Some((e, _, members)) = composite_entry_exit.get(&to)
&& let Some(e) = e.as_ref().or_else(|| members.first())
{
to = e.clone();
}
let (shape_f, hint_f) = node_meta(&from, from_is_star, false, false);
push_node(
nodes,
seen,
from.clone(),
labels.get(&from).cloned().flatten(),
shape_f,
hint_f,
);
let (shape_t, hint_t) = node_meta(&to, false, to_is_star, false);
push_node(
nodes,
seen,
to.clone(),
labels.get(&to).cloned().flatten(),
shape_t,
hint_t,
);
push_edge(edges, edge_counter, from, to, t.label.clone());
}
(entry, exit)
}
let degraded = transition_seen_first(sd);
collect(
sd,
&mut nodes,
&mut edges,
&mut subgraphs,
&mut seen,
&labels,
&mut composite_entry_exit,
&mut edge_counter,
false,
°raded,
None,
);
for e in &edges {
if !seen.contains(&e.source) {
let (shape, hint) = node_meta(&e.source, false, false, false);
push_node(
&mut nodes,
&mut seen,
e.source.clone(),
labels.get(&e.source).cloned().flatten(),
shape,
hint,
);
}
if !seen.contains(&e.target) {
let (shape, hint) = node_meta(&e.target, false, false, false);
push_node(
&mut nodes,
&mut seen,
e.target.clone(),
labels.get(&e.target).cloned().flatten(),
shape,
hint,
);
}
}
Unigraph {
family: ir::unigraph::GraphFamily::Directed,
direction: DEFAULT_DIRECTION,
nodes,
edges,
subgraphs,
sequence_rows: None,
meta: ir::common::DiagramMeta {
title: None,
show_data: false,
},
}
}