mermaid-text 0.56.0

Render Mermaid diagrams as Unicode box-drawing text — no browser, no image protocols, pure Rust
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
//! Parser for Mermaid `requirementDiagram` diagrams.
//!
//! Accepted syntax:
//!
//! ```text
//! requirementDiagram
//!
//!     requirement test_req {
//!         id: 1
//!         text: the test text.
//!         risk: high
//!         verifymethod: test
//!     }
//!
//!     element test_entity {
//!         type: simulation
//!         docref: reqs/test_entity
//!     }
//!
//!     test_entity - satisfies -> test_req
//! ```
//!
//! Rules:
//! - `requirementDiagram` keyword is required as the first non-blank,
//!   non-comment line (case-sensitive; Mermaid spells it camelCase).
//! - Requirement blocks: `<kind> <name> { id: … text: … risk: … verifymethod: … }`.
//!   `id:` and `text:` are required; `risk:` and `verifymethod:` are optional.
//! - Element blocks: `element <name> { type: … docref: … }`.
//!   `type:` is required; `docref:` is optional.
//! - Relationship lines: `<source> - <kind> -> <target>`.
//! - `%%` comment lines, blank lines, and `accTitle`/`accDescr` lines are
//!   silently skipped.
//! - Unknown lines outside blocks are silently ignored for forward compatibility.
//!
//! # Examples
//!
//! ```
//! use mermaid_text::parser::requirement_diagram::parse;
//!
//! let src = "requirementDiagram\n    requirement r1 {\n        id: 1\n        text: some text.\n    }";
//! let diag = parse(src).unwrap();
//! assert_eq!(diag.requirements.len(), 1);
//! assert_eq!(diag.requirements[0].name, "r1");
//! assert_eq!(diag.requirements[0].id, "1");
//! assert_eq!(diag.requirements[0].text, "some text.");
//! ```

use crate::Error;
use crate::parser::common::strip_inline_comment;
use crate::requirement_diagram::{
    Element, RelationshipKind, Requirement, RequirementDiagram, RequirementKind,
    RequirementRelationship, Risk, VerifyMethod,
};

/// Parse a `requirementDiagram` source string into a [`RequirementDiagram`].
///
/// # Errors
///
/// - [`Error::ParseError`] — missing `requirementDiagram` header, missing
///   required `id:` or `text:` field inside a requirement block, or a
///   malformed relationship arrow.
pub fn parse(src: &str) -> Result<RequirementDiagram, Error> {
    let mut header_seen = false;
    let mut diag = RequirementDiagram::default();

    // Block parsing state: we accumulate lines inside `{ … }` until we
    // hit the matching `}` at the same or lower indent level.
    let mut in_block = false;
    let mut block_kind: BlockKind = BlockKind::Requirement(RequirementKind::default());
    let mut block_name = String::new();
    let mut block_lines: Vec<String> = Vec::new();

    for raw in src.lines() {
        let stripped = strip_inline_comment(raw);
        let trimmed = stripped.trim();

        if !header_seen {
            if trimmed.is_empty() || trimmed.starts_with("%%") {
                continue;
            }
            // Case-sensitive per spec; Mermaid's detector is camelCase-exact
            // for requirementDiagram. We accept it case-insensitively for
            // robustness (matches how the detector module handles it).
            if !trimmed.eq_ignore_ascii_case("requirementDiagram") {
                return Err(Error::ParseError(format!(
                    "expected `requirementDiagram` header, got {trimmed:?}"
                )));
            }
            header_seen = true;
            continue;
        }

        // Skip blank lines and full-line comments.
        if trimmed.is_empty() || trimmed.starts_with("%%") {
            continue;
        }

        // Silently skip accessibility metadata.
        if trimmed.starts_with("accTitle") || trimmed.starts_with("accDescr") {
            continue;
        }

        if in_block {
            if trimmed == "}" {
                // Close the current block and parse its accumulated lines.
                in_block = false;
                match block_kind {
                    BlockKind::Requirement(kind) => {
                        let req = parse_requirement_block(kind, &block_name, &block_lines)?;
                        diag.requirements.push(req);
                    }
                    BlockKind::Element => {
                        let elem = parse_element_block(&block_name, &block_lines)?;
                        diag.elements.push(elem);
                    }
                }
                block_lines.clear();
                block_name.clear();
            } else {
                block_lines.push(trimmed.to_string());
            }
            continue;
        }

        // Try to open a new block.
        if let Some((kind, name)) = try_parse_block_header(trimmed) {
            in_block = true;
            block_kind = kind;
            block_name = name;
            block_lines.clear();
            continue;
        }

        // Try to parse a relationship line: `source - kind -> target`
        if let Some(rel) = try_parse_relationship(trimmed)? {
            diag.relationships.push(rel);
            continue;
        }

        // Unknown top-level line: silently ignore for forward compatibility.
    }

    if !header_seen {
        return Err(Error::ParseError(
            "missing `requirementDiagram` header line".to_string(),
        ));
    }

    Ok(diag)
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Discriminant for block types during multi-line parsing.
#[derive(Debug, Clone, Copy)]
enum BlockKind {
    Requirement(RequirementKind),
    Element,
}

/// Match a line like `requirement foo {` or `element bar {`.
///
/// Returns `(BlockKind, name)` if the line opens a block, otherwise `None`.
fn try_parse_block_header(line: &str) -> Option<(BlockKind, String)> {
    // All block headers end with ` {` or just `{`.
    // We need to strip the trailing `{` and optional whitespace.
    let body = if let Some(b) = line.strip_suffix('{') {
        b.trim()
    } else {
        return None;
    };

    // Split on the first whitespace: keyword + name.
    let (keyword, rest) = body.split_once(char::is_whitespace)?;
    let name = rest.trim().to_string();
    if name.is_empty() {
        return None;
    }

    let kind = match keyword.to_lowercase().as_str() {
        "requirement" => BlockKind::Requirement(RequirementKind::Requirement),
        "functionalrequirement" => BlockKind::Requirement(RequirementKind::Functional),
        "interfacerequirement" => BlockKind::Requirement(RequirementKind::Interface),
        "performancerequirement" => BlockKind::Requirement(RequirementKind::Performance),
        "physicalrequirement" => BlockKind::Requirement(RequirementKind::Physical),
        "designconstraint" => BlockKind::Requirement(RequirementKind::DesignConstraint),
        "element" => BlockKind::Element,
        _ => return None,
    };
    Some((kind, name))
}

/// Parse the key-value fields of a requirement block.
///
/// `id:` and `text:` are required; missing either returns [`Error::ParseError`].
fn parse_requirement_block(
    kind: RequirementKind,
    name: &str,
    lines: &[String],
) -> Result<Requirement, Error> {
    let mut id: Option<String> = None;
    let mut text: Option<String> = None;
    let mut risk: Option<Risk> = None;
    let mut verify_method: Option<VerifyMethod> = None;

    for line in lines {
        let trimmed = line.trim();
        if let Some(val) = trimmed.strip_prefix("id:") {
            id = Some(val.trim().to_string());
        } else if let Some(val) = trimmed.strip_prefix("text:") {
            text = Some(val.trim().to_string());
        } else if let Some(val) = trimmed.strip_prefix("risk:") {
            risk = parse_risk(val.trim());
        } else if let Some(val) = trimmed.strip_prefix("verifymethod:") {
            verify_method = parse_verify_method(val.trim());
        }
        // Unknown fields are silently ignored.
    }

    let id = id.ok_or_else(|| {
        Error::ParseError(format!(
            "requirement {name:?} is missing required `id:` field"
        ))
    })?;
    let text = text.ok_or_else(|| {
        Error::ParseError(format!(
            "requirement {name:?} is missing required `text:` field"
        ))
    })?;

    Ok(Requirement {
        kind,
        name: name.to_string(),
        id,
        text,
        risk,
        verify_method,
    })
}

/// Parse the key-value fields of an element block.
///
/// `type:` is required; missing it returns [`Error::ParseError`].
fn parse_element_block(name: &str, lines: &[String]) -> Result<Element, Error> {
    let mut kind: Option<String> = None;
    let mut docref: Option<String> = None;

    for line in lines {
        let trimmed = line.trim();
        if let Some(val) = trimmed.strip_prefix("type:") {
            kind = Some(val.trim().to_string());
        } else if let Some(val) = trimmed.strip_prefix("docref:") {
            docref = Some(val.trim().to_string());
        }
        // Unknown fields are silently ignored.
    }

    let kind = kind.ok_or_else(|| {
        Error::ParseError(format!(
            "element {name:?} is missing required `type:` field"
        ))
    })?;

    Ok(Element {
        name: name.to_string(),
        kind,
        docref,
    })
}

/// Try to parse a relationship line of the form `source - kind -> target`.
///
/// Returns `Ok(Some(rel))` on success, `Ok(None)` if the line does not look
/// like a relationship at all, and `Err(...)` when the line contains ` - `
/// but has malformed arrow syntax.
fn try_parse_relationship(line: &str) -> Result<Option<RequirementRelationship>, Error> {
    // A relationship line must contain both ` - ` and ` -> `.
    let Some(dash_pos) = line.find(" - ") else {
        return Ok(None);
    };

    let source = line[..dash_pos].trim().to_string();
    let after_dash = &line[dash_pos + 3..]; // skip " - "

    let Some(arrow_pos) = after_dash.find(" -> ") else {
        return Err(Error::ParseError(format!(
            "malformed relationship — expected `source - kind -> target`, got {line:?}"
        )));
    };

    let kind_str = after_dash[..arrow_pos].trim();
    let target = after_dash[arrow_pos + 4..].trim().to_string(); // skip " -> "

    if source.is_empty() || target.is_empty() {
        return Err(Error::ParseError(format!(
            "malformed relationship — source or target is empty in {line:?}"
        )));
    }

    let kind = match kind_str.to_lowercase().as_str() {
        "contains" => RelationshipKind::Contains,
        "copies" => RelationshipKind::Copies,
        "derives" => RelationshipKind::Derives,
        "satisfies" => RelationshipKind::Satisfies,
        "verifies" => RelationshipKind::Verifies,
        "refines" => RelationshipKind::Refines,
        "traces" => RelationshipKind::Traces,
        other => {
            return Err(Error::ParseError(format!(
                "unknown relationship kind {other:?} in {line:?}"
            )));
        }
    };

    Ok(Some(RequirementRelationship {
        source,
        target,
        kind,
    }))
}

fn parse_risk(s: &str) -> Option<Risk> {
    match s.to_lowercase().as_str() {
        "low" => Some(Risk::Low),
        "medium" => Some(Risk::Medium),
        "high" => Some(Risk::High),
        _ => None,
    }
}

fn parse_verify_method(s: &str) -> Option<VerifyMethod> {
    match s.to_lowercase().as_str() {
        "analysis" => Some(VerifyMethod::Analysis),
        "inspection" => Some(VerifyMethod::Inspection),
        "test" => Some(VerifyMethod::Test),
        "demonstration" => Some(VerifyMethod::Demonstration),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    const HEADER: &str = "requirementDiagram\n";

    fn minimal_req(name: &str) -> String {
        format!(
            "{HEADER}    requirement {name} {{\n        id: 1\n        text: some text.\n    }}"
        )
    }

    // 1. Minimal: header + 1 requirement
    #[test]
    fn parses_minimal_requirement_diagram() {
        let src = minimal_req("r1");
        let diag = parse(&src).unwrap();
        assert_eq!(diag.requirements.len(), 1);
        assert_eq!(diag.requirements[0].name, "r1");
        assert_eq!(diag.requirements[0].id, "1");
        assert_eq!(diag.requirements[0].text, "some text.");
        assert_eq!(diag.requirements[0].kind, RequirementKind::Requirement);
    }

    // 2. All 6 requirement kinds
    #[test]
    fn parses_all_six_requirement_kinds() {
        let src = format!(
            "{HEADER}\
            requirement r1 {{\n    id: 1\n    text: t.\n}}\n\
            functionalRequirement r2 {{\n    id: 2\n    text: t.\n}}\n\
            interfaceRequirement r3 {{\n    id: 3\n    text: t.\n}}\n\
            performanceRequirement r4 {{\n    id: 4\n    text: t.\n}}\n\
            physicalRequirement r5 {{\n    id: 5\n    text: t.\n}}\n\
            designConstraint r6 {{\n    id: 6\n    text: t.\n}}"
        );
        let diag = parse(&src).unwrap();
        assert_eq!(diag.requirements.len(), 6);
        assert_eq!(diag.requirements[0].kind, RequirementKind::Requirement);
        assert_eq!(diag.requirements[1].kind, RequirementKind::Functional);
        assert_eq!(diag.requirements[2].kind, RequirementKind::Interface);
        assert_eq!(diag.requirements[3].kind, RequirementKind::Performance);
        assert_eq!(diag.requirements[4].kind, RequirementKind::Physical);
        assert_eq!(diag.requirements[5].kind, RequirementKind::DesignConstraint);
    }

    // 3. Element with type only
    #[test]
    fn parses_element_with_type_only() {
        let src = format!("{HEADER}element e1 {{\n    type: simulation\n}}");
        let diag = parse(&src).unwrap();
        assert_eq!(diag.elements.len(), 1);
        assert_eq!(diag.elements[0].name, "e1");
        assert_eq!(diag.elements[0].kind, "simulation");
        assert!(diag.elements[0].docref.is_none());
    }

    // 4. Element with type + docref
    #[test]
    fn parses_element_with_type_and_docref() {
        let src =
            format!("{HEADER}element e2 {{\n    type: word doc\n    docref: reqs/test_entity\n}}");
        let diag = parse(&src).unwrap();
        assert_eq!(diag.elements.len(), 1);
        assert_eq!(diag.elements[0].kind, "word doc");
        assert_eq!(
            diag.elements[0].docref,
            Some("reqs/test_entity".to_string())
        );
    }

    // 5. All 7 relationship kinds
    #[test]
    fn parses_all_seven_relationship_kinds() {
        let src = format!(
            "{HEADER}\
            a - contains -> b\n\
            a - copies -> b\n\
            a - derives -> b\n\
            a - satisfies -> b\n\
            a - verifies -> b\n\
            a - refines -> b\n\
            a - traces -> b"
        );
        let diag = parse(&src).unwrap();
        assert_eq!(diag.relationships.len(), 7);
        assert_eq!(diag.relationships[0].kind, RelationshipKind::Contains);
        assert_eq!(diag.relationships[1].kind, RelationshipKind::Copies);
        assert_eq!(diag.relationships[2].kind, RelationshipKind::Derives);
        assert_eq!(diag.relationships[3].kind, RelationshipKind::Satisfies);
        assert_eq!(diag.relationships[4].kind, RelationshipKind::Verifies);
        assert_eq!(diag.relationships[5].kind, RelationshipKind::Refines);
        assert_eq!(diag.relationships[6].kind, RelationshipKind::Traces);
    }

    // 6. Risk + verifymethod fields
    #[test]
    fn parses_risk_and_verifymethod_fields() {
        let src = format!(
            "{HEADER}requirement r1 {{\n\
                id: 1\n\
                text: t.\n\
                risk: medium\n\
                verifymethod: inspection\n\
            }}"
        );
        let diag = parse(&src).unwrap();
        let req = &diag.requirements[0];
        assert_eq!(req.risk, Some(Risk::Medium));
        assert_eq!(req.verify_method, Some(VerifyMethod::Inspection));
    }

    // 7. Missing required id: returns error
    #[test]
    fn missing_id_returns_error() {
        let src = format!("{HEADER}requirement r1 {{\n    text: some text.\n}}");
        let err = parse(&src).unwrap_err();
        assert!(
            err.to_string().contains("id"),
            "error message should mention missing id: {err}"
        );
    }

    // 8. Missing required text: returns error
    #[test]
    fn missing_text_returns_error() {
        let src = format!("{HEADER}requirement r1 {{\n    id: 1\n}}");
        let err = parse(&src).unwrap_err();
        assert!(
            err.to_string().contains("text"),
            "error message should mention missing text: {err}"
        );
    }

    // 9. Comment lines are skipped
    #[test]
    fn comment_lines_skipped() {
        let src = format!(
            "%% preamble\n{HEADER}\
            %% inner comment\n\
            requirement r1 {{\n\
                id: 1\n\
                text: some text. %% trailing\n\
            }}"
        );
        let diag = parse(&src).unwrap();
        assert_eq!(diag.requirements.len(), 1);
    }

    // 10. Malformed relationship arrow returns error
    #[test]
    fn malformed_relationship_arrow_returns_error() {
        // Contains ` - ` but missing ` -> `.
        let src = format!("{HEADER}a - satisfies b");
        let err = parse(&src).unwrap_err();
        assert!(
            err.to_string().contains("malformed"),
            "expected malformed error, got: {err}"
        );
    }

    // 11. Full canonical example parses completely
    #[test]
    fn parses_canonical_example() {
        let src = "requirementDiagram

    requirement test_req {
        id: 1
        text: the test text.
        risk: high
        verifymethod: test
    }

    functionalRequirement test_req2 {
        id: 1.1
        text: the second test text.
        risk: low
        verifymethod: inspection
    }

    element test_entity {
        type: simulation
    }

    element test_entity2 {
        type: word doc
        docref: reqs/test_entity
    }

    test_entity - satisfies -> test_req2
    test_req - traces -> test_req2
    test_req - contains -> test_req";

        let diag = parse(src).unwrap();
        assert_eq!(diag.requirements.len(), 2);
        assert_eq!(diag.elements.len(), 2);
        assert_eq!(diag.relationships.len(), 3);

        let req = &diag.requirements[0];
        assert_eq!(req.name, "test_req");
        assert_eq!(req.id, "1");
        assert_eq!(req.risk, Some(Risk::High));
        assert_eq!(req.verify_method, Some(VerifyMethod::Test));

        let elem = &diag.elements[1];
        assert_eq!(elem.kind, "word doc");
        assert_eq!(elem.docref, Some("reqs/test_entity".to_string()));

        assert_eq!(diag.relationships[0].kind, RelationshipKind::Satisfies);
        assert_eq!(diag.relationships[0].source, "test_entity");
        assert_eq!(diag.relationships[0].target, "test_req2");
    }

    // 12. All verify methods are parsed
    #[test]
    fn parses_all_verify_methods() {
        for (kw, expected) in &[
            ("analysis", VerifyMethod::Analysis),
            ("inspection", VerifyMethod::Inspection),
            ("test", VerifyMethod::Test),
            ("demonstration", VerifyMethod::Demonstration),
        ] {
            let src = format!(
                "{HEADER}requirement r1 {{\n    id: 1\n    text: t.\n    verifymethod: {kw}\n}}"
            );
            let diag = parse(&src).unwrap();
            assert_eq!(
                diag.requirements[0].verify_method,
                Some(*expected),
                "failed for verifymethod={kw}"
            );
        }
    }
}