Mermaid.js Railroad EBNF Syntax Guide

Mermaid.js provides dedicated syntax designed specifically to build Railroad diagrams from Extended Backus-Naur Form (EBNF) definitions. With plain-text production rules, you can visually represent formal language grammars, parser expressions, and command syntaxes using intuitive visual tracks and decision branches.

1. Core EBNF Operators & Syntax

In EBNF syntax diagrams, production rules use standard formal grammar notation to define terminals, non-terminals, choices, and repetitions along a visual track.
EBNF Notation Railroad Meaning Description
rule = ... ; Production Rule Defines a named grammar rule ended with a semicolon
"literal" Terminal Node Represents exact characters or keywords enclosed in double quotes
| Choice Branch Branches the track into mutually exclusive alternatives
( ... )* Zero-or-More Loop Creates a returning loop track for elements that can repeat 0 or more times
+ One-or-More Loop Indicates an element that must occur at least once
railroad-ebnf-beta
    title "Basic Token Rule"

    identifier = letter ( letter | digit )* ;
    letter = "a" | "b" | "c" ;
    digit = "0" | "1" | "2" ;

Syntax railroad diagram created with VPasCode illustrating grammar rules for identifier, letter, and digit production rules.


2. Arithmetic Expression Grammar Example

Use production rules to model nested language structures such as mathematical expressions, operator precedence, and parenthesized grouping.
railroad-ebnf-beta
    title "Arithmetic Expression Grammar"

    expression = term ( ( "+" | "-" ) term )* ;
    term = factor ( ( "*" | "/" ) factor )* ;
    factor = number | "(" expression ")" ;
    number = digit+ ;
    digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;

Syntax railroad diagram created with VPasCode illustrating arithmetic expression grammar rules for expression, term, factor, number, and digit.


3. Command & Query Language Example

The following example demonstrates a complete SQL query production rule set mapped directly from EBNF notation into a visual railroad syntax diagram.
railroad-ebnf-beta
    title "SQL Statement Grammar"

    select_statement = "SELECT" column_clause "FROM" table_name [ where_clause ] ;
    column_clause = "*" | column_name ( "," column_name )* ;
    where_clause = "WHERE" condition ;
    table_name = identifier ;
    column_name = identifier ;
    identifier = "a" | "b" | "c" ;

Syntax railroad diagram created with VPasCode illustrating SQL SELECT statement grammar rules including column_clause, where_clause, table_name, and identifier.


Conclusion

Using Mermaid’s EBNF syntax gives language designers, compiler engineers, and technical writers a clean, code-driven way to document formal grammars. By declaring production rules directly, you can automatically generate self-documenting syntax diagrams alongside your technical specifications.
Scroll to Top