1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use super::{Edge, Node, Stmt, TitleKind, apply_shape_data_value_to_node};
use crate::diagram::{DiagramWarningFact, FLOWCHART_UNKNOWN_STYLE_TARGET_WARNING_RULE_ID};
use crate::{ParseControl, ParseControlResult};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
pub(super) struct FlowchartBuildState {
pub(super) nodes: Vec<Node>,
pub(super) node_index: HashMap<String, usize>,
pub(super) edges: Vec<Edge>,
pub(super) used_edge_ids: HashSet<String>,
pub(super) subgraph_ids: HashSet<String>,
pub(super) edge_pair_counts: HashMap<(String, String), usize>,
pub(super) vertex_calls: Vec<String>,
pub(super) warning_facts: Vec<DiagramWarningFact>,
}
impl FlowchartBuildState {
pub(super) fn new(subgraph_ids: HashSet<String>) -> Self {
Self {
nodes: Vec::new(),
node_index: HashMap::new(),
edges: Vec::new(),
used_edge_ids: HashSet::new(),
subgraph_ids,
edge_pair_counts: HashMap::new(),
vertex_calls: Vec::new(),
warning_facts: Vec::new(),
}
}
pub(super) fn add_statements(
&mut self,
statements: &[Stmt],
shape_data_documents: &HashMap<String, std::result::Result<Value, String>>,
control: &ParseControl,
) -> ParseControlResult<std::result::Result<(), String>> {
// Keep Mermaid's preorder statement handling without using the Rust call stack for
// deeply nested subgraphs.
let mut stack = vec![statements.iter()];
let mut visited = 0usize;
while let Some(iter) = stack.last_mut() {
let Some(stmt) = iter.next() else {
stack.pop();
continue;
};
if visited.is_multiple_of(128) {
control.checkpoint()?;
}
visited = visited.saturating_add(1);
match stmt {
Stmt::Chain { nodes, edges } => {
let mut deferred_shape_data_vertex_calls: Vec<String> = Vec::new();
for (index, mut n) in nodes.iter().cloned().enumerate() {
if index % 128 == 0 {
control.checkpoint()?;
}
// Mermaid FlowDB `vertexCounter` increments on every `addVertex(...)` call.
// Our grammar models `shapeData` attachments in the AST, so we can replay the
// observable call sequence:
// - once for the vertex token itself
// - once more if a `@{ ... }` shapeData block is present
self.vertex_calls.push(n.id.clone());
if n.shape_data.is_some() {
// For multi-vertex statements (notably `&`-separated nodes), the upstream
// parser's reduction order can apply shapeData after the statement's
// vertices have already been introduced. Record these shapeData calls
// after we've visited every vertex in the statement.
deferred_shape_data_vertex_calls.push(n.id.clone());
}
if let Some(sd) = n.shape_data.take()
&& let Err(error) =
apply_shape_data_document(&mut n, &sd, shape_data_documents)
{
return Ok(Err(error));
}
self.upsert_node(n);
}
for (index, id) in deferred_shape_data_vertex_calls.into_iter().enumerate() {
if index % 128 == 0 {
control.checkpoint()?;
}
self.vertex_calls.push(id);
}
for (index, e) in edges.iter().cloned().enumerate() {
if index % 128 == 0 {
control.checkpoint()?;
}
self.push_edge(e);
}
}
Stmt::Node(n) => {
let mut n = n.as_ref().clone();
self.vertex_calls.push(n.id.clone());
if n.shape_data.is_some() {
self.vertex_calls.push(n.id.clone());
}
if let Some(sd) = n.shape_data.take()
&& let Err(error) =
apply_shape_data_document(&mut n, &sd, shape_data_documents)
{
return Ok(Err(error));
}
self.upsert_node(n);
}
Stmt::ShapeData {
target,
target_span,
..
} => {
// Mermaid applies shapeData to edges if (and only if) an edge with that ID exists.
// For ordering parity we only insert a placeholder node when this currently refers to a node.
if !self.used_edge_ids.contains(target) {
// The upstream flowchart parser calls `addVertex(id)` and then
// `addVertex(id, ..., shapeData)` for `id@{...}` statements.
self.vertex_calls.push(target.clone());
self.vertex_calls.push(target.clone());
}
if !self.used_edge_ids.contains(target) && !self.node_index.contains_key(target)
{
let idx = self.nodes.len();
self.nodes.push(Node {
id: target.clone(),
id_span: *target_span,
label: None,
label_type: TitleKind::Text,
label_span: None,
label_selection: None,
shape: None,
shape_data: None,
icon: None,
form: None,
pos: None,
img: None,
constraint: None,
asset_width: None,
asset_height: None,
styles: Vec::new(),
classes: Vec::new(),
link: None,
link_target: None,
have_callback: false,
});
self.node_index.insert(target.clone(), idx);
}
}
Stmt::Subgraph(sg) => stack.push(sg.statements.iter()),
Stmt::Direction(_)
| Stmt::ClassDef(_)
| Stmt::ClassAssign(_)
| Stmt::Click(_)
| Stmt::LinkStyle(_) => {}
Stmt::Style(s) => {
// Mermaid still advances the vertex counter for `style <subgraph-id>`.
// Record that observable call, but do not synthesize a node or warning
// for subgraph targets because the style belongs to the cluster.
if self.subgraph_ids.contains(&s.target) {
self.vertex_calls.push(s.target.clone());
continue;
}
// Mermaid's `style` statement routes through FlowDB `addVertex(id, ..., styles)`.
// This increments `vertexCounter` for nodes (but is a no-op for edges).
if !self.used_edge_ids.contains(&s.target) {
self.vertex_calls.push(s.target.clone());
if !self.node_index.contains_key(&s.target) {
let mut warning = DiagramWarningFact::new(
FLOWCHART_UNKNOWN_STYLE_TARGET_WARNING_RULE_ID,
format!(
"Style applied to unknown node \"{}\". This may indicate a typo. The node will be created automatically.",
s.target
),
);
if let Some(span) = s.target_span {
warning = warning.with_span(span);
}
self.warning_facts.push(warning);
let idx = self.nodes.len();
self.nodes.push(Node {
id: s.target.clone(),
id_span: None,
label: None,
label_type: TitleKind::Text,
label_span: None,
label_selection: None,
shape: None,
shape_data: None,
icon: None,
form: None,
pos: None,
img: None,
constraint: None,
asset_width: None,
asset_height: None,
styles: Vec::new(),
classes: Vec::new(),
link: None,
link_target: None,
have_callback: false,
});
self.node_index.insert(s.target.clone(), idx);
}
}
}
}
}
control.checkpoint()?;
Ok(Ok(()))
}
fn upsert_node(&mut self, n: Node) {
if let Some(&idx) = self.node_index.get(&n.id) {
if n.label.is_some() {
self.nodes[idx].label = n.label;
self.nodes[idx].label_type = n.label_type;
self.nodes[idx].label_span = n.label_span;
self.nodes[idx].label_selection = n.label_selection;
}
if n.shape.is_some() {
self.nodes[idx].shape = n.shape;
}
if n.icon.is_some() {
self.nodes[idx].icon = n.icon;
}
if n.form.is_some() {
self.nodes[idx].form = n.form;
}
if n.pos.is_some() {
self.nodes[idx].pos = n.pos;
}
if n.img.is_some() {
self.nodes[idx].img = n.img;
}
if n.constraint.is_some() {
self.nodes[idx].constraint = n.constraint;
}
if n.asset_width.is_some() {
self.nodes[idx].asset_width = n.asset_width;
}
if n.asset_height.is_some() {
self.nodes[idx].asset_height = n.asset_height;
}
self.nodes[idx].styles.extend(n.styles);
self.nodes[idx].classes.extend(n.classes);
return;
}
let idx = self.nodes.len();
self.node_index.insert(n.id.clone(), idx);
self.nodes.push(n);
}
fn push_edge(&mut self, mut e: Edge) {
let key = (e.from.clone(), e.to.clone());
let existing = *self.edge_pair_counts.get(&key).unwrap_or(&0);
let mut final_id = e.id.clone();
let mut is_user_defined_id = false;
if let Some(user_id) = e.id.clone() {
if !self.used_edge_ids.contains(&user_id) {
is_user_defined_id = true;
self.used_edge_ids.insert(user_id);
} else {
final_id = None;
}
}
if final_id.is_none() {
let counter = if existing == 0 { 0 } else { existing + 1 };
final_id = Some(format!("L_{}_{}_{}", e.from, e.to, counter));
if let Some(id) = final_id.clone() {
self.used_edge_ids.insert(id);
}
}
self.edge_pair_counts.insert(key, existing + 1);
e.id = final_id;
e.is_user_defined_id = is_user_defined_id;
e.link.length = e.link.length.min(10);
self.edges.push(e);
}
}
fn apply_shape_data_document(
node: &mut Node,
source: &str,
documents: &HashMap<String, std::result::Result<Value, String>>,
) -> std::result::Result<(), String> {
match documents
.get(source)
.expect("flowchart shape data must be prepared before semantic construction")
{
Ok(document) => apply_shape_data_value_to_node(node, document),
Err(error) => Err(error.clone()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn single_large_chain_observes_cancellation_inside_node_projection() {
let nodes = (0..256)
.map(|index| Node {
id: format!("n{index}"),
id_span: None,
label: None,
label_type: TitleKind::Text,
label_span: None,
label_selection: None,
shape: None,
shape_data: None,
icon: None,
form: None,
pos: None,
img: None,
constraint: None,
asset_width: None,
asset_height: None,
styles: Vec::new(),
classes: Vec::new(),
link: None,
link_target: None,
have_callback: false,
})
.collect();
let statements = [Stmt::Chain {
nodes,
edges: Vec::new(),
}];
let mut build = FlowchartBuildState::new(HashSet::new());
let control = ParseControl::new();
control.cancel_after_checkpoints(2);
assert!(matches!(
build.add_statements(&statements, &HashMap::new(), &control),
Err(crate::ParseCancelled)
));
assert!(build.nodes.len() < 256);
}
}