merman-core 0.4.2

Mermaid parser + semantic model (headless; parity-focused).
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use crate::{Error, ParseMetadata, Result};
use serde_json::Value;

/// Parses a ZenUML diagram into a Mermaid-like semantic model.
///
/// Upstream Mermaid integrates ZenUML via the `mermaid-zenuml` external diagram package, which
/// uses `@zenuml/core` in the browser. `merman` is headless and pure Rust, so for now we implement
/// a conservative compatibility mode: a small ZenUML subset is translated into Mermaid
/// `sequenceDiagram` syntax and then parsed by the existing sequence parser.
///
/// This is intended to support basic `Actor->Actor: message` diagrams for headless integrations.
pub fn parse_zenuml(code: &str, meta: &ParseMetadata) -> Result<Value> {
    let mut out: Vec<String> = vec!["sequenceDiagram".to_string()];

    let mut saw_header = false;
    let mut pending_comments: Vec<String> = Vec::new();
    let mut pending_return_annotator: bool = false;

    #[derive(Debug, Clone)]
    enum BlockKind {
        Loop,
        Opt,
        Par { branch_started: bool },
        IfAlt,
        TryAlt,
        SyncCall { actor: String },
    }

    fn starts_with_word_ci(haystack: &str, word: &str) -> bool {
        haystack
            .get(0..word.len())
            .is_some_and(|p| p.eq_ignore_ascii_case(word))
            && haystack
                .get(word.len()..word.len() + 1)
                .is_none_or(|c| c.chars().all(|ch| ch.is_ascii_whitespace() || ch == '('))
    }

    fn strip_trailing_open_brace(line: &str) -> Option<&str> {
        let trimmed = line.trim_end();
        trimmed.strip_suffix('{').map(str::trim_end)
    }

    fn translate_participant_decl(line: &str) -> Option<String> {
        // Participant order control:
        //   Bob
        //   Alice
        //
        // Annotators:
        //   @Actor Alice
        //   @Database Bob
        //
        // Aliases:
        //   A as Alice
        //   J as John
        let l = line.trim();
        if l.is_empty() {
            return None;
        }

        if let Some(rest) = l.strip_prefix('@') {
            let (kind, name) = rest.split_once(' ')?;
            let kind = kind.trim();
            let name = name.trim();
            if name.is_empty() {
                return None;
            }
            // Mermaid `sequenceDiagram` supports a limited set of participant kinds in our
            // headless parser today. Keep this translation conservative so fixtures can be
            // snapshot-gated deterministically.
            let kw = if kind.eq_ignore_ascii_case("actor") {
                "actor"
            } else {
                // `@Database`, `@Boundary`, etc. are represented as standard participants.
                "participant"
            };
            return Some(format!("{kw} {name}"));
        }

        if let Some((id, label)) = l.split_once(" as ") {
            let id = id.trim();
            let label = label.trim();
            if id.is_empty() || label.is_empty() {
                return None;
            }
            // ZenUML uses `A as Alice` where `A` is used in messages and `Alice` is the label.
            // Mermaid sequence supports `participant Alice as A` (label first, alias second).
            return Some(format!("participant {label} as {id}"));
        }

        // Bare participant/actor declaration (single token).
        if l.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
        {
            return Some(format!("participant {l}"));
        }

        None
    }

    fn translate_assignment(line: &str) -> Option<(String, String, String)> {
        // Minimal supported syntax (ZenUML docs "Reply message"):
        //   a = A.SyncMessage()
        //   SomeType a = A.SyncMessage()
        //
        // Returns (var, actor, call_text).
        let (lhs, rhs) = line.split_once('=')?;
        let lhs = lhs.trim();
        let rhs = rhs.trim();
        if lhs.is_empty() || rhs.is_empty() {
            return None;
        }

        let var = lhs.split_whitespace().last()?.trim();
        if var.is_empty() {
            return None;
        }

        let (actor, call) = rhs.split_once('.')?;
        let actor = actor.trim();
        let call = call.trim();
        if actor.is_empty() || call.is_empty() {
            return None;
        }

        Some((var.to_string(), actor.to_string(), call.to_string()))
    }

    fn translate_message_line(line: &str) -> Option<String> {
        // Minimal supported syntax:
        //   Alice->Bob: Hello
        //   Bob-->Alice: Reply
        //
        // Map to Mermaid sequence syntax:
        //   Alice->>Bob: Hello
        //   Bob-->>Alice: Reply
        let (lhs, label) = if let Some((a, b)) = line.split_once(':') {
            (a.trim(), Some(b.trim()))
        } else {
            (line.trim(), None)
        };

        let (from, arrow, to) = if let Some((a, b)) = lhs.split_once("-->") {
            (a.trim(), "-->", b.trim())
        } else if let Some((a, b)) = lhs.split_once("->") {
            (a.trim(), "->", b.trim())
        } else {
            return None;
        };

        if from.is_empty() || to.is_empty() {
            return None;
        }

        let seq_arrow = match arrow {
            "-->" => "-->>",
            "->" => "->>",
            _ => return None,
        };

        let mut out = String::new();
        out.push_str(from);
        out.push_str(seq_arrow);
        out.push_str(to);
        if let Some(lbl) = label {
            if !lbl.is_empty() {
                out.push_str(": ");
                out.push_str(lbl);
            }
        }
        Some(out)
    }

    fn flush_pending_comments_as_notes(
        pending: &mut Vec<String>,
        out: &mut Vec<String>,
        from: &str,
        to: &str,
    ) {
        if pending.is_empty() {
            return;
        }
        for c in pending.drain(..) {
            let text = c.trim();
            if text.is_empty() {
                continue;
            }
            // ZenUML comments are rendered above messages/fragments. Approximate this behavior
            // by emitting a Mermaid sequence note spanning the message participants.
            out.push(format!("Note over {from},{to}: {text}"));
        }
    }

    let mut stack: Vec<BlockKind> = Vec::new();

    fn par_maybe_and(stack: &mut [BlockKind], out: &mut Vec<String>) {
        let Some(BlockKind::Par { branch_started }) = stack.last_mut() else {
            return;
        };
        if *branch_started {
            out.push("and".to_string());
        } else {
            *branch_started = true;
        }
    }

    fn close_brace(rest: &str, stack: &mut Vec<BlockKind>, out: &mut Vec<String>) {
        let Some(top) = stack.last() else {
            return;
        };

        // For `if { ... } else { ... }` and `try { ... } catch { ... }`, the brace before the next
        // branch must *not* close the translated Mermaid fragment.
        match top {
            BlockKind::IfAlt => {
                if rest.starts_with("else") {
                    return;
                }
            }
            BlockKind::TryAlt => {
                if rest.starts_with("catch") || rest.starts_with("finally") {
                    return;
                }
            }
            BlockKind::SyncCall { .. } => {}
            _ => {}
        }

        let closed = stack.pop();
        match closed {
            Some(BlockKind::SyncCall { actor }) => {
                out.push(format!("deactivate {actor}"));
            }
            Some(_) => {
                out.push("end".to_string());
            }
            None => {}
        }
    }

    for raw in code.lines() {
        let mut line = raw.trim();
        if line.is_empty() {
            continue;
        }

        if !saw_header && line.to_ascii_lowercase().starts_with("zenuml") {
            saw_header = true;
            continue;
        }

        // ZenUML renders `// ...` comments above the following messages/fragments.
        // - a comment on a participant will not be rendered
        // - a comment on a message should be rendered
        if let Some(c) = line.strip_prefix("//") {
            pending_comments.push(c.trim().to_string());
            continue;
        }

        // ZenUML reply annotators:
        //   @return
        //   @reply
        //
        // These affect the next message. We approximate this by forcing the next message to use
        // a Mermaid-style "return" arrow (`-->>`) regardless of the original arrow.
        if line.eq_ignore_ascii_case("@return") || line.eq_ignore_ascii_case("@reply") {
            pending_return_annotator = true;
            continue;
        }

        // Handle leading close braces, including `} else {` and `} catch {` forms.
        loop {
            let trimmed = line.trim_start();
            if !trimmed.starts_with('}') {
                line = trimmed;
                break;
            }
            let rest = trimmed[1..].trim_start();
            close_brace(rest, &mut stack, &mut out);
            line = rest;
            if line.is_empty() {
                break;
            }
        }
        if line.is_empty() {
            continue;
        }

        // Pass through common metadata directives as-is when possible.
        if line.to_ascii_lowercase().starts_with("title ") {
            out.push(line.to_string());
            pending_comments.clear();
            continue;
        }
        if line.to_ascii_lowercase().starts_with("acctitle ") {
            out.push(line.to_string());
            pending_comments.clear();
            continue;
        }
        if line.to_ascii_lowercase().starts_with("accdescr ") {
            out.push(line.to_string());
            pending_comments.clear();
            continue;
        }

        // Branch continuations for `if` and `try` structures.
        if let Some(prefix) = strip_trailing_open_brace(line) {
            let p = prefix.trim();
            if starts_with_word_ci(p, "else if") {
                let Some((_, cond)) = p.split_once('(') else {
                    return Err(Error::DiagramParse {
                        diagram_type: meta.diagram_type.clone(),
                        message: format!("unsupported zenuml statement: {line}"),
                    });
                };
                let Some((cond, _)) = cond.rsplit_once(')') else {
                    return Err(Error::DiagramParse {
                        diagram_type: meta.diagram_type.clone(),
                        message: format!("unsupported zenuml statement: {line}"),
                    });
                };
                let label = format!("if({})", cond.trim());
                out.push(format!("else {label}"));
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "else") {
                out.push("else".to_string());
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "catch") {
                out.push("else catch".to_string());
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "finally") {
                out.push("else finally".to_string());
                pending_comments.clear();
                continue;
            }
        }

        // Block openings.
        if let Some(prefix) = strip_trailing_open_brace(line) {
            let p = prefix.trim();

            if starts_with_word_ci(p, "while") {
                par_maybe_and(&mut stack, &mut out);
                out.push(format!("loop {p}"));
                stack.push(BlockKind::Loop);
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "for")
                || starts_with_word_ci(p, "foreach")
                || starts_with_word_ci(p, "forEach")
                || starts_with_word_ci(p, "loop")
            {
                par_maybe_and(&mut stack, &mut out);
                out.push(format!("loop {p}"));
                stack.push(BlockKind::Loop);
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "opt") {
                par_maybe_and(&mut stack, &mut out);
                let label = p.strip_prefix("opt").unwrap_or("").trim();
                if label.is_empty() {
                    out.push("opt".to_string());
                } else {
                    out.push(format!("opt {label}"));
                }
                stack.push(BlockKind::Opt);
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "par") {
                par_maybe_and(&mut stack, &mut out);
                let label = p.strip_prefix("par").unwrap_or("").trim();
                if label.is_empty() {
                    out.push("par".to_string());
                } else {
                    out.push(format!("par {label}"));
                }
                stack.push(BlockKind::Par {
                    branch_started: false,
                });
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "if") {
                par_maybe_and(&mut stack, &mut out);
                let Some((_, cond)) = p.split_once('(') else {
                    return Err(Error::DiagramParse {
                        diagram_type: meta.diagram_type.clone(),
                        message: format!("unsupported zenuml statement: {line}"),
                    });
                };
                let Some((cond, _)) = cond.rsplit_once(')') else {
                    return Err(Error::DiagramParse {
                        diagram_type: meta.diagram_type.clone(),
                        message: format!("unsupported zenuml statement: {line}"),
                    });
                };
                out.push(format!("alt if({})", cond.trim()));
                stack.push(BlockKind::IfAlt);
                pending_comments.clear();
                continue;
            }
            if starts_with_word_ci(p, "try") {
                par_maybe_and(&mut stack, &mut out);
                out.push("alt try".to_string());
                stack.push(BlockKind::TryAlt);
                pending_comments.clear();
                continue;
            }

            // Sync message / method-call blocks:
            //   A.SyncMessage(with, parameters) { ... }
            //
            // Translate to a self-message plus explicit activation scope.
            if let Some((actor, method)) = p.split_once('.') {
                let actor = actor.trim();
                let method = method.trim();
                if !actor.is_empty() && !method.is_empty() {
                    par_maybe_and(&mut stack, &mut out);
                    flush_pending_comments_as_notes(&mut pending_comments, &mut out, actor, actor);
                    out.push(format!("{actor}->>{actor}: {method}"));
                    out.push(format!("activate {actor}"));
                    stack.push(BlockKind::SyncCall {
                        actor: actor.to_string(),
                    });
                    continue;
                }
            }
        }

        // Creation messages:
        //   new A1
        //   new A2(with, parameters)
        if let Some(rest) = line.strip_prefix("new ") {
            let rest = rest.trim();
            if rest.is_empty() {
                return Err(Error::DiagramParse {
                    diagram_type: meta.diagram_type.clone(),
                    message: format!("unsupported zenuml statement: {line}"),
                });
            }

            // Extract a stable id for Mermaid sequence: the leading identifier token.
            let chars = rest.chars();
            let mut id = String::new();
            for ch in chars {
                if ch.is_ascii_alphanumeric() || ch == '_' || ch == '.' {
                    id.push(ch);
                } else {
                    break;
                }
            }
            if id.is_empty() {
                return Err(Error::DiagramParse {
                    diagram_type: meta.diagram_type.clone(),
                    message: format!("unsupported zenuml statement: {line}"),
                });
            }

            par_maybe_and(&mut stack, &mut out);
            pending_comments.clear();

            // If the creation has arguments, keep the full text as the label (description).
            if rest != id {
                out.push(format!("create participant {id} as {rest}"));
            } else {
                out.push(format!("create participant {id}"));
            }
            continue;
        }

        // Participants.
        if let Some(decl) = translate_participant_decl(line) {
            par_maybe_and(&mut stack, &mut out);
            out.push(decl);
            // ZenUML comment on a participant is not rendered.
            pending_comments.clear();
            continue;
        }

        // Reply assignments must be handled before generic `Actor.Method(...)` parsing, because
        // an assignment line contains a `.` and would otherwise be misinterpreted as a sync call.
        if let Some((var, actor, call)) = translate_assignment(line) {
            par_maybe_and(&mut stack, &mut out);
            flush_pending_comments_as_notes(&mut pending_comments, &mut out, &actor, &actor);
            out.push(format!("{actor}->>{actor}: {call} => {var}"));
            pending_return_annotator = false;
            continue;
        }

        // Sync messages without blocks:
        //   A.SyncMessage
        //   A.SyncMessage(with, parameters)
        if let Some((actor, method)) = line.split_once('.') {
            let actor = actor.trim();
            let method = method.trim();
            if !actor.is_empty() && !method.is_empty() {
                par_maybe_and(&mut stack, &mut out);
                flush_pending_comments_as_notes(&mut pending_comments, &mut out, actor, actor);
                out.push(format!("{actor}->>{actor}: {method}"));
                continue;
            }
        }

        // Return statements inside sync call blocks.
        if let Some(rest) = line.strip_prefix("return ") {
            let Some(actor) = stack.last().and_then(|b| match b {
                BlockKind::SyncCall { actor } => Some(actor.clone()),
                _ => None,
            }) else {
                return Err(Error::DiagramParse {
                    diagram_type: meta.diagram_type.clone(),
                    message: format!("unsupported zenuml statement: {line}"),
                });
            };
            par_maybe_and(&mut stack, &mut out);
            flush_pending_comments_as_notes(&mut pending_comments, &mut out, &actor, &actor);
            out.push(format!("{actor}-->>{actor}: {}", rest.trim()));
            pending_return_annotator = false;
            continue;
        }

        if let Some(mut seq_line) = translate_message_line(line) {
            par_maybe_and(&mut stack, &mut out);
            let (lhs, _) = if let Some((a, b)) = line.split_once(':') {
                (a.trim(), Some(b.trim()))
            } else {
                (line.trim(), None)
            };
            let (from, to) = if let Some((a, b)) = lhs.split_once("-->") {
                (a.trim(), b.trim())
            } else if let Some((a, b)) = lhs.split_once("->") {
                (a.trim(), b.trim())
            } else {
                ("", "")
            };
            flush_pending_comments_as_notes(&mut pending_comments, &mut out, from, to);
            if pending_return_annotator {
                // Convert `->>` to `-->>` for return/reply.
                seq_line = seq_line.replace("->>", "-->>");
                pending_return_annotator = false;
            }
            out.push(seq_line);
            continue;
        }

        return Err(Error::DiagramParse {
            diagram_type: meta.diagram_type.clone(),
            message: format!("unsupported zenuml statement: {line}"),
        });
    }

    crate::diagrams::sequence::parse_sequence(&out.join("\n"), meta)
}

#[cfg(test)]
mod tests {
    use crate::{Engine, ParseOptions};

    #[test]
    fn zenuml_basic_translates_to_sequence_model() {
        let engine = Engine::new();
        let input = "zenuml\n  Alice->Bob: Hello\n  Bob-->Alice: Reply\n";
        let parsed =
            futures::executor::block_on(engine.parse_diagram(input, ParseOptions::lenient()))
                .unwrap()
                .unwrap();
        assert_eq!(parsed.meta.diagram_type, "zenuml");
        assert!(parsed.model.get("messages").is_some());
    }

    #[test]
    fn zenuml_participants_and_fragments_translate_to_sequence_model() {
        let engine = Engine::new();
        let input = r#"zenuml
title Demo
Bob
Alice
Alice->Bob: Hi Bob
while(true) {
  Bob->Alice: Hi Alice
}
if(is_sick) {
  Bob->Alice: Not so good :(
} else {
  Bob->Alice: Feeling fresh
}
opt {
  Bob->Alice: Thanks
}
par {
  Alice->Bob: Hello guys!
  Alice->John: Hello guys!
}
"#;
        let parsed =
            futures::executor::block_on(engine.parse_diagram(input, ParseOptions::lenient()))
                .unwrap()
                .unwrap();
        assert_eq!(parsed.meta.diagram_type, "zenuml");
        assert!(parsed.model.get("messages").is_some());
    }

    #[test]
    fn zenuml_reply_message_forms_translate() {
        let engine = Engine::new();
        let input = r#"zenuml
SomeType a = A.SyncMessage()
a = A.SyncMessage()
A.SyncMessage() {
  return result
}
@return
A->B: ok
"#;
        let parsed =
            futures::executor::block_on(engine.parse_diagram(input, ParseOptions::lenient()))
                .unwrap()
                .unwrap();
        assert_eq!(parsed.meta.diagram_type, "zenuml");
        assert!(parsed.model.get("messages").is_some());
    }
}