ariel-rs 0.1.1

A faithful Rust port of Mermaid JS — headless SVG diagram rendering without a browser
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
/// Parser for Mermaid Railroad (syntax/grammar) diagram syntax.
///
/// Faithful port of the Railroad diagram grammar from railroadDb.ts.
///
/// Grammar (EBNF-like notation used by Mermaid):
///   railroad
///   [title <text>]
///   <rule_name> ::= <expression>
///   <rule_name> = <expression>
///
/// Expressions (EBNF):
///   terminal     — quoted string: "text" or 'text'
///   nonterminal  — unquoted identifier
///   sequence     — expr expr ...
///   choice       — expr | expr | ...
///   optional     — [ expr ]
///   repetition*  — { expr }   (zero or more)
///   repetition+  — expr+      (one or more, or { expr }+ if needed)
///   group        — ( expr )
///   special      — ? text ?
///
/// The parser produces an AST of ASTNode variants.

#[derive(Debug, Clone)]
pub enum AstNode {
    Terminal(String),
    NonTerminal(String),
    Sequence(Vec<AstNode>),
    Choice(Vec<AstNode>),
    Optional(Box<AstNode>),
    Repetition { element: Box<AstNode>, min: u32 }, // min=0 → *, min=1 → +
    Special(String),
}

#[derive(Debug, Clone)]
pub struct RailroadRule {
    pub name: String,
    pub definition: AstNode,
    pub comment: Option<String>,
}

pub struct RailroadDiagram {
    pub title: Option<String>,
    pub rules: Vec<RailroadRule>,
}

pub fn parse(input: &str) -> crate::error::ParseResult<RailroadDiagram> {
    let mut title: Option<String> = None;
    let mut rules: Vec<RailroadRule> = Vec::new();
    let mut header_seen = false;

    // Accumulate lines into rule definitions (which may span multiple lines)
    let mut pending_rule: Option<(String, String, Option<String>)> = None;

    for raw_line in input.lines() {
        let trimmed = raw_line.trim();

        if trimmed.is_empty() || trimmed.starts_with("%%") {
            continue;
        }

        if !header_seen {
            let lower = trimmed.to_lowercase();
            if lower == "railroad"
                || lower == "railroad-beta"
                || lower.starts_with("railroad ")
                || lower.starts_with("railroad-beta ")
            {
                header_seen = true;
                continue;
            }
            continue;
        }

        // title
        if trimmed.to_lowercase().starts_with("title ") {
            title = Some(trimmed[6..].trim().to_string());
            continue;
        }

        // Comment extraction (// at end of line or standalone)
        let (line_content, comment) = split_comment(trimmed);
        let line_content = line_content.trim();

        if line_content.is_empty() {
            continue;
        }

        // Check for rule definition: "name ::= expr" or "name = expr"
        // Must check "::=" before "="
        let rule_sep = if line_content.contains("::=") {
            Some("::=")
        } else if let Some(eq_pos) = find_rule_equals(line_content) {
            let _ = eq_pos;
            Some("=")
        } else {
            None
        };

        if let Some(sep) = rule_sep {
            // Flush previous pending rule
            if let Some((name, expr_str, cmt)) = pending_rule.take() {
                if let Some(rule) = build_rule(&name, &expr_str, cmt) {
                    rules.push(rule);
                }
            }

            let parts: Vec<&str> = line_content.splitn(2, sep).collect();
            if parts.len() == 2 {
                let name = parts[0].trim().to_string();
                let expr_str = parts[1].trim().to_string();
                pending_rule = Some((name, expr_str, comment.map(|s| s.to_string())));
            }
        } else if pending_rule.is_some() {
            // Continuation of previous rule
            if let Some((_, ref mut expr_str, _)) = pending_rule {
                expr_str.push(' ');
                expr_str.push_str(line_content);
            }
        }
    }

    // Flush last rule
    if let Some((name, expr_str, cmt)) = pending_rule {
        if let Some(rule) = build_rule(&name, &expr_str, cmt) {
            rules.push(rule);
        }
    }

    crate::error::ParseResult::ok(RailroadDiagram { title, rules })
}

/// Split a line into (content, optional comment after //)
fn split_comment(s: &str) -> (&str, Option<&str>) {
    if let Some(pos) = find_comment_pos(s) {
        (&s[..pos], Some(s[pos + 2..].trim()))
    } else {
        (s, None)
    }
}

fn find_comment_pos(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    let mut in_single = false;
    let mut in_double = false;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\'' if !in_double => in_single = !in_single,
            b'"' if !in_single => in_double = !in_double,
            b'/' if !in_single && !in_double && bytes.get(i + 1) == Some(&b'/') => return Some(i),
            _ => {}
        }
        i += 1;
    }
    None
}

/// Find the position of a bare '=' that is not part of '::='
fn find_rule_equals(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    for i in 0..bytes.len() {
        if bytes[i] == b'=' {
            // Check it's not part of ::=
            if i > 0 && bytes[i - 1] == b':' {
                continue;
            }
            // Check it's not ==, >=, <=, !=
            if bytes.get(i + 1) == Some(&b'=') {
                continue;
            }
            if i > 0 && (bytes[i - 1] == b'>' || bytes[i - 1] == b'<' || bytes[i - 1] == b'!') {
                continue;
            }
            return Some(i);
        }
    }
    None
}

fn build_rule(name: &str, expr_str: &str, comment: Option<String>) -> Option<RailroadRule> {
    if name.is_empty() {
        return None;
    }
    let definition = parse_expression(expr_str.trim())?;
    Some(RailroadRule {
        name: name.to_string(),
        definition,
        comment,
    })
}

// ── Expression parser ─────────────────────────────────────────────────────────

struct Parser<'a> {
    input: &'a [u8],
    pos: usize,
}

impl<'a> Parser<'a> {
    fn new(s: &'a str) -> Self {
        Parser {
            input: s.as_bytes(),
            pos: 0,
        }
    }

    fn peek(&self) -> Option<u8> {
        self.input.get(self.pos).copied()
    }

    fn consume(&mut self) -> Option<u8> {
        let b = self.input.get(self.pos).copied();
        if b.is_some() {
            self.pos += 1;
        }
        b
    }

    fn skip_ws(&mut self) {
        while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
            self.pos += 1;
        }
    }

    #[allow(dead_code)]
    fn at_end(&self) -> bool {
        self.pos >= self.input.len()
    }

    #[allow(dead_code)]
    fn rest(&self) -> &str {
        std::str::from_utf8(&self.input[self.pos..]).unwrap_or("")
    }

    /// Parse a choice expression (highest precedence = lowest binding).
    fn parse_choice(&mut self) -> Option<AstNode> {
        let first = self.parse_sequence()?;
        self.skip_ws();

        if self.peek() != Some(b'|') {
            return Some(first);
        }

        let mut alternatives = vec![first];
        while self.peek() == Some(b'|') {
            self.consume(); // consume '|'
            self.skip_ws();
            let next = self.parse_sequence()?;
            alternatives.push(next);
            self.skip_ws();
        }
        Some(AstNode::Choice(alternatives))
    }

    /// Parse a sequence of atoms.
    fn parse_sequence(&mut self) -> Option<AstNode> {
        let mut elements = Vec::new();
        loop {
            self.skip_ws();
            // Stop at | ) ] }  or end
            match self.peek() {
                None | Some(b'|' | b')' | b']' | b'}') => break,
                _ => {}
            }
            if let Some(atom) = self.parse_atom() {
                elements.push(atom);
            } else {
                break;
            }
        }
        match elements.len() {
            0 => None,
            1 => Some(elements.remove(0)),
            _ => Some(AstNode::Sequence(elements)),
        }
    }

    /// Parse a single atom (terminal, nonterminal, group, optional, repetition, special).
    fn parse_atom(&mut self) -> Option<AstNode> {
        self.skip_ws();
        let b = self.peek()?;

        match b {
            // Terminal: "..." or '...'
            b'"' | b'\'' => {
                let quote = self.consume().unwrap();
                let mut text = String::new();
                loop {
                    match self.consume() {
                        Some(c) if c == quote => break,
                        Some(c) => text.push(c as char),
                        None => break,
                    }
                }
                // Check for + suffix (one or more repetition)
                let min = if self.peek() == Some(b'+') {
                    self.consume();
                    1
                } else if self.peek() == Some(b'*') {
                    self.consume();
                    0
                } else {
                    return Some(AstNode::Terminal(text));
                };
                Some(AstNode::Repetition {
                    element: Box::new(AstNode::Terminal(text)),
                    min,
                })
            }

            // Group: (...)
            b'(' => {
                self.consume();
                let inner = self.parse_choice()?;
                self.skip_ws();
                if self.peek() == Some(b')') {
                    self.consume();
                }
                // Suffix?
                let min_opt = match self.peek() {
                    Some(b'+') => {
                        self.consume();
                        Some(1u32)
                    }
                    Some(b'*') => {
                        self.consume();
                        Some(0u32)
                    }
                    Some(b'?') => {
                        self.consume();
                        None
                    } // optional
                    _ => return Some(inner),
                };
                match min_opt {
                    Some(min) => Some(AstNode::Repetition {
                        element: Box::new(inner),
                        min,
                    }),
                    None => Some(AstNode::Optional(Box::new(inner))),
                }
            }

            // Optional: [...]
            b'[' => {
                self.consume();
                let inner = self.parse_choice()?;
                self.skip_ws();
                if self.peek() == Some(b']') {
                    self.consume();
                }
                Some(AstNode::Optional(Box::new(inner)))
            }

            // Repetition / group: {...}
            b'{' => {
                self.consume();
                let inner = self.parse_choice()?;
                self.skip_ws();
                if self.peek() == Some(b'}') {
                    self.consume();
                }
                // {expr} = zero-or-more; {expr}+ = one-or-more
                let min = if self.peek() == Some(b'+') {
                    self.consume();
                    1
                } else {
                    0
                };
                Some(AstNode::Repetition {
                    element: Box::new(inner),
                    min,
                })
            }

            // Special: ?...?
            b'?' => {
                self.consume();
                let mut text = String::new();
                loop {
                    match self.consume() {
                        Some(b'?') => break,
                        Some(c) => text.push(c as char),
                        None => break,
                    }
                }
                Some(AstNode::Special(text.trim().to_string()))
            }

            // Nonterminal: identifier
            _ if (b as char).is_alphanumeric() || b == b'_' || b == b'-' => {
                let mut ident = String::new();
                while let Some(c) = self.peek() {
                    if (c as char).is_alphanumeric() || c == b'_' || c == b'-' {
                        ident.push(c as char);
                        self.consume();
                    } else {
                        break;
                    }
                }
                // Suffix
                let node = AstNode::NonTerminal(ident);
                match self.peek() {
                    Some(b'+') => {
                        self.consume();
                        Some(AstNode::Repetition {
                            element: Box::new(node),
                            min: 1,
                        })
                    }
                    Some(b'*') => {
                        self.consume();
                        Some(AstNode::Repetition {
                            element: Box::new(node),
                            min: 0,
                        })
                    }
                    Some(b'?') => {
                        self.consume();
                        Some(AstNode::Optional(Box::new(node)))
                    }
                    _ => Some(node),
                }
            }

            _ => {
                // Unknown character — skip it
                self.consume();
                None
            }
        }
    }
}

fn parse_expression(s: &str) -> Option<AstNode> {
    if s.is_empty() {
        return None;
    }
    let mut p = Parser::new(s);
    let node = p.parse_choice()?;
    // If nothing was parsed but there's still input, return a nonterminal of the raw string
    Some(node)
}

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

    #[test]
    fn basic_rule() {
        let input = "railroad\n    title My Grammar\n    digit ::= \"0\" | \"1\" | \"2\"\n";
        let d = parse(input).diagram;
        assert_eq!(d.title.as_deref(), Some("My Grammar"));
        assert_eq!(d.rules.len(), 1);
        assert_eq!(d.rules[0].name, "digit");
        match &d.rules[0].definition {
            AstNode::Choice(alts) => assert_eq!(alts.len(), 3),
            other => panic!("Expected Choice, got {:?}", other),
        }
    }

    #[test]
    fn sequence_rule() {
        let input = "railroad\n    expr = term ((\"+\" | \"-\") term)*\n";
        let d = parse(input).diagram;
        assert_eq!(d.rules.len(), 1);
    }

    #[test]
    fn optional_rule() {
        let input = "railroad\n    opt_rule = [\"a\" | \"b\"]\n";
        let d = parse(input).diagram;
        let def = &d.rules[0].definition;
        match def {
            AstNode::Optional(_) => {}
            other => panic!("Expected Optional, got {:?}", other),
        }
    }

    #[test]
    fn repetition_rule() {
        let input = "railroad\n    list = { item }+\n";
        let d = parse(input).diagram;
        match &d.rules[0].definition {
            AstNode::Repetition { min, .. } => assert_eq!(*min, 1),
            other => panic!("Expected Repetition, got {:?}", other),
        }
    }
}