use crate::{
ast::{ArrowType, Flowchart, NodeShape},
builder::ir::{
self,
common::{
ArrowKind, ArrowSpec, EdgePriority, LabelSpec, LineKind, PortHint, PortSet, SizeHint,
StyleRef,
},
shape::ShapeKind,
unigraph::{EdgeKind, UGEdge, UGNode, Unigraph},
},
};
pub fn map_shape(shape: &Option<NodeShape>) -> ShapeKind {
match shape {
None => ShapeKind::Rectangle,
Some(NodeShape::Rectangle) => ShapeKind::Rectangle,
Some(NodeShape::Rounded) => ShapeKind::Rounded,
Some(NodeShape::Stadium) => ShapeKind::Stadium,
Some(NodeShape::Subroutine) => ShapeKind::Subroutine,
Some(NodeShape::Diamond) => ShapeKind::Diamond,
Some(NodeShape::Hexagon) => ShapeKind::Hexagon,
Some(NodeShape::Circle) => ShapeKind::Circle,
Some(NodeShape::DoubleCircle) => ShapeKind::DoubleCircle,
Some(NodeShape::Cylinder) => ShapeKind::Cylinder,
Some(NodeShape::Asymmetric) => ShapeKind::Asymmetric,
Some(NodeShape::Parallelogram) | Some(NodeShape::ParallelogramAlt) => {
ShapeKind::Parallelogram
}
Some(NodeShape::Trapezoid) | Some(NodeShape::TrapezoidAlt) => ShapeKind::Trapezoid,
}
}
pub fn map_arrow(arrow: &ArrowType) -> ArrowSpec {
let (start, end) = match arrow {
ArrowType::Solid | ArrowType::Thick | ArrowType::Dotted => {
(ArrowKind::None, ArrowKind::Arrow)
}
ArrowType::NoArrow => (ArrowKind::None, ArrowKind::None),
ArrowType::Invisible => (ArrowKind::None, ArrowKind::None),
ArrowType::Both => (ArrowKind::Arrow, ArrowKind::Arrow),
ArrowType::Circle => (ArrowKind::None, ArrowKind::Circle),
ArrowType::Cross => (ArrowKind::None, ArrowKind::Cross),
ArrowType::MultiCircle => (ArrowKind::Circle, ArrowKind::Circle),
ArrowType::MultiCross => (ArrowKind::Cross, ArrowKind::Cross),
};
ArrowSpec { start, end }
}
pub fn map_line(arrow: &ArrowType) -> LineKind {
match arrow {
ArrowType::Solid
| ArrowType::NoArrow
| ArrowType::Both
| ArrowType::Circle
| ArrowType::Cross
| ArrowType::MultiCircle
| ArrowType::MultiCross => LineKind::Solid,
ArrowType::Dotted => LineKind::Dotted,
ArrowType::Thick => LineKind::Thick,
ArrowType::Invisible => LineKind::Invisible,
}
}
fn flow_edge(e: &crate::ast::Edge, i: usize, direction: Option<crate::ast::Direction>) -> UGEdge {
let (src_port, tgt_port) = match direction {
Some(crate::ast::Direction::LR) | Some(crate::ast::Direction::RL) => {
(PortHint::Right, PortHint::Left)
}
_ => (PortHint::Bottom, PortHint::Top),
};
UGEdge {
id: format!("e{}", i),
source: e.source.clone(),
target: e.target.clone(),
source_port: src_port,
target_port: tgt_port,
kind: EdgeKind::Flow,
label_text: e.label.clone(),
label: None,
priority: EdgePriority::Primary,
routing_hint: ir::common::RoutingHint::Spline,
arrow: map_arrow(&e.arrow_type),
line_kind: map_line(&e.arrow_type),
repulsion: 1.0,
cardinality: (None, None),
cardinality_text: (None, None),
}
}
fn walk_subgraphs<'a>(sg: &'a crate::ast::Subgraph, f: &mut impl FnMut(&'a crate::ast::Subgraph)) {
f(sg);
for child in &sg.subgraphs {
walk_subgraphs(child, f);
}
}
fn collect_subgraph_nodes<'a>(sg: &'a crate::ast::Subgraph, out: &mut Vec<&'a crate::ast::Node>) {
out.extend(sg.nodes.iter());
for child in &sg.subgraphs {
collect_subgraph_nodes(child, out);
}
}
fn collect_subgraph_edges<'a>(sg: &'a crate::ast::Subgraph, out: &mut Vec<&'a crate::ast::Edge>) {
out.extend(sg.edges.iter());
for child in &sg.subgraphs {
collect_subgraph_edges(child, out);
}
}
fn subgraph_member_ids(sg: &crate::ast::Subgraph, out: &mut Vec<String>) {
out.extend(sg.nodes.iter().map(|n| n.id.clone()));
for child in &sg.subgraphs {
subgraph_member_ids(child, out);
}
}
pub fn extract_flowchart(fc: &Flowchart) -> Unigraph {
use std::collections::HashMap;
let mut shape_of: HashMap<&str, &Option<NodeShape>> = HashMap::new();
let mut text_of: HashMap<&str, &Option<String>> = HashMap::new();
for n in &fc.nodes {
shape_of.insert(n.id.as_str(), &n.shape);
text_of.insert(n.id.as_str(), &n.text);
}
for sg in &fc.subgraphs {
walk_subgraphs(sg, &mut |sub| {
for n in &sub.nodes {
shape_of.insert(n.id.as_str(), &n.shape);
text_of.insert(n.id.as_str(), &n.text);
}
});
}
let mut nodes = Vec::new();
let mut seen = std::collections::HashSet::new();
let mut emit_node = |nodes: &mut Vec<UGNode>,
id: &str,
shape_of: &HashMap<&str, &Option<NodeShape>>,
text_of: &HashMap<&str, &Option<String>>| {
if seen.contains(id) {
return;
}
seen.insert(id.to_string());
let shape = map_shape(shape_of.get(id).copied().unwrap_or(&None));
let label = LabelSpec {
text: text_of
.get(id)
.and_then(|o| o.as_ref())
.cloned()
.unwrap_or_else(|| id.to_string()),
spans: Vec::new(), };
nodes.push(UGNode {
id: id.to_string(),
kind: ir::common::NodeKind::Atom,
role: ir::common::NodeRole::Atom,
shape,
label: ir::common::LabelOrMeasured::Spec(label),
ports: PortSet::default(),
size_hint: SizeHint::ByText,
style_ref: StyleRef::NodeDefault,
constraint: ir::common::NodeConstraint::Free,
detail: ir::common::NodeDetail::None,
});
};
for n in &fc.nodes {
emit_node(&mut nodes, &n.id, &shape_of, &text_of);
}
let mut sub_nodes: Vec<&crate::ast::Node> = Vec::new();
for sg in &fc.subgraphs {
collect_subgraph_nodes(sg, &mut sub_nodes);
}
for n in sub_nodes {
emit_node(&mut nodes, &n.id, &shape_of, &text_of);
}
let mut edges = Vec::new();
let mut edge_idx = 0usize;
let mut sub_edges: Vec<&crate::ast::Edge> = Vec::new();
for sg in &fc.subgraphs {
collect_subgraph_edges(sg, &mut sub_edges);
}
for e in sub_edges {
edges.push(flow_edge(e, edge_idx, fc.direction));
edge_idx += 1;
}
for e in &fc.edges {
edges.push(flow_edge(e, edge_idx, fc.direction));
edge_idx += 1;
}
let mut subgraphs: Vec<ir::unigraph::UGSubgraph> = Vec::new();
for sg in &fc.subgraphs {
walk_subgraphs(sg, &mut |sub| {
let mut member_ids = Vec::new();
subgraph_member_ids(sub, &mut member_ids);
subgraphs.push(ir::unigraph::UGSubgraph {
id: format!("sub{}", subgraphs.len()),
title: sub.title.clone(),
member_ids,
direction: sub.direction,
kind: ir::common::ContainerKind::Subgraph,
});
});
}
Unigraph {
family: ir::unigraph::GraphFamily::Directed,
direction: fc.direction.unwrap_or(crate::ast::Direction::TB),
nodes,
edges,
subgraphs,
sequence_rows: None,
meta: ir::common::DiagramMeta {
title: None,
show_data: false,
},
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(src: &str) -> Flowchart {
crate::MermaidParser::parse_mermaid(src)
.map(|d| match d {
crate::ast::Diagram::Flowchart(f) => f,
_ => panic!("not a flowchart"),
})
.expect("parse")
}
#[test]
fn subgraph_internal_edges_are_collected() {
let fc = parse(
"flowchart TD\nA[Start]\nsubgraph One\nB[Process]\nC[Decision]\nB --> C\nend\nA --> B\n",
);
let ug = extract_flowchart(&fc);
assert_eq!(ug.edges.len(), 2, "子图内部边不得丢失");
let pairs: Vec<(String, String)> = ug
.edges
.iter()
.map(|e| (e.source.clone(), e.target.clone()))
.collect();
assert!(
pairs.contains(&("B".into(), "C".into())),
"缺子图内部边 B→C"
);
assert!(pairs.contains(&("A".into(), "B".into())), "缺跨子图边 A→B");
let ids: Vec<String> = ug.edges.iter().map(|e| e.id.clone()).collect();
assert_eq!(ids, vec!["e0", "e1"]);
}
#[test]
fn nested_subgraphs_keep_hierarchy() {
let fc = parse(
"flowchart TD\nsubgraph outer\nsubgraph inner\nA[In] --> B[Inner]\nend\nC[Outer] --> A\nend\nD --> C\n",
);
let ug = extract_flowchart(&fc);
assert_eq!(ug.subgraphs.len(), 2, "内层与外层各一个容器");
let outer = &ug.subgraphs[0];
let inner = &ug.subgraphs[1];
assert_eq!(outer.title.as_deref(), Some("outer"));
assert_eq!(inner.title.as_deref(), Some("inner"));
assert!(inner.member_ids.iter().any(|id| id == "A"));
assert!(
outer.member_ids.iter().any(|id| id == "A"),
"外层成员应包含内层节点"
);
assert!(outer.member_ids.len() > inner.member_ids.len());
assert_eq!(ug.nodes.len(), 4);
assert_eq!(ug.edges.len(), 3, "内层边与跨层边都不得丢失");
}
#[test]
fn duplicate_node_declaration_last_wins() {
let fc = parse("flowchart TD\nA[First]\nA[Second]\nA --> B[End]\n");
let ug = extract_flowchart(&fc);
let a = ug.nodes.iter().find(|n| n.id == "A").expect("node A");
match &a.label {
crate::builder::ir::common::LabelOrMeasured::Spec(s) => {
assert_eq!(s.text, "Second", "后出现的定义应覆盖先出现的");
}
other => panic!("expected Spec label, got {other:?}"),
}
assert_eq!(ug.nodes.len(), 2, "同名节点只应出现一次");
}
#[test]
fn flowchart_dispatch_is_case_insensitive_and_trims_leading_space() {
for src in [
"flowchart TD\nA[Start] --> B[End]\n",
"Flowchart TD\nA[Start] --> B[End]\n",
" flowchart TD\nA[Start] --> B[End]\n",
"graph LR\nA[Start] --> B[End]\n",
] {
let fc = parse(src);
assert_eq!(fc.edges.len(), 1, "src: {src:?}");
}
}
}