Skip to content
Projets

tabatkins/railroad-diagrams

Voir sur GitHub

À propos

:steam_locomotive: Une petite bibliothèque JS+SVG pour dessiner des diagrammes syntaxiques ferroviaires, comme ceux de JSON.org. Disponible désormais aussi en version Python !

Design et médias

Comment ces chiffres sont mesurés

Progression mesurée des étoiles

in 24h
0
in 7 days
+1
in 15 days
+3
in 1 month
+4

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

Railroad-diagram Generator

Diagram(Stack('Generate', 'some'), OneOrMore(NonTerminal('railroad diagrams'), Comment('and more')))

        ╭──────────╮
├┼──────│ Generate │──┐
        ╰──────────╯  │
     ┌────────────────┘
     │    ╭──────╮           ┌───────────────────┐
     └────│ some │────────╭──│ railroad diagrams │──╮───┼┤
          ╰──────╯        │  └───────────────────┘  │
                          ╰─and more────────────────╯
(If this one looks messed up, you're probably on ChromeOS or Android,
 whose default monospace fonts don't include box-drawing characters,
 meaning it's falling back to a variable-width font for those chars.
 I can't adjust font on GitHub READMEs, but you can make sure *your*
 text editor or website uses a monospace font with proper support,
 so it'll look great when you generate text-based diagrams yourself.)

This is a small library for generating railroad diagrams (like what JSON.org uses) using SVG or Unicode/ASCII text, with both JavaScript and Python implementations.

Railroad diagrams are a way of visually representing a grammar in a form that is more readable than using regular expressions or BNF. They can easily represent any context-free grammar, and some more powerful grammars. There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted, so I wrote my own.

Libraries

This repository contains both the JavaScript and Python implementations with equivalent functionality:

Input Syntaxes

In addition to constructing diagrams programmatically, both the Python and JavaScript libraries (and the online generator) can parse diagrams from two text formats via parse(source, syntax="auto"), parseDsl(source), and parseKdl(source).

In both formats, command/node names are matched case-insensitively and ignore - and _ (so OneOrMore, one-or-more, and one_or_more are all equivalent), and top-level items are implicitly wrapped in a Diagram unless the document consists of a single top-level Diagram or ComplexDiagram.

Indentation DSL

An indentation-based mini-language originally created for Bikeshed. Each element occupies a single line, with children indented beneath their parent:

Stack:
	Or: 1
		T: --
		Seq:
			Opt: skip
				T: -
			Or:
				N: a-z A-Z _ or non-ASCII
				N: escape
	Star:
		Or:
			N: a-z A-Z 0-9 _ - or non-ASCII
			N: escape

Structure rules:

  • Blank lines are ignored.
  • Common leading whitespace from the first non-blank line is stripped from all lines; any line indented less than the first line is a ParseError.
  • The first indented line determines the single indent unit (defaulting to a single tab \t if no line is indented). Indentation may increase by at most one level per line.
  • Block commands take their optional prelude after the colon: Command: [prelude], with children indented on following lines.
  • Leaf commands take their optional prelude before the colon and their text after the colon: Command [prelude]: text, and cannot have children.

Block commands:

Command Aliases Prelude Children
Diagram simple (default) or complex 0+ (sole top-level command only)
ComplexDiagram (none) 0+ (sole top-level command only)
Sequence Seq, And (none) 1+
Stack (none) 1+
OptionalSequence OptSeq (none) 1+
AlternatingSequence AltSeq (none) Exactly 2
Choice Or Integer default branch index (default 0) 1+
HorizontalChoice HChoice (none) 1+
MultipleChoice MChoice [index] [any|all] (defaults 0, any) 1+
Optional Opt (empty) or skip Exactly 1
OneOrMore Plus (none) 1 or 2 (item, optional repeat)
ZeroOrMore Star (empty) or skip 1 or 2 (item, optional repeat)
Group Optional label text 1 (or 2 without prelude: item, label)

Leaf commands:

Command Aliases Prelude (before :) Text (after :)
Terminal T Optional href Terminal text
NonTerminal N Optional href Non-terminal text
Comment C Optional href Comment text
Skip S (none) (none)
Start simple (default) or complex Optional label text
End simple (default) or complex (none)
Block (none) Space-separated key=value pairs (width, up, height, down, needs-space/needsSpace)
Style (none) CSS string

Example using leaf href preludes and extended containers:

ComplexDiagram:
	Start complex: expr
	Group: operands
		MultipleChoice: 1 all
			Terminal #op-a: a
			NonTerminal #op-b: ident
	End complex:

KDL 2.0

A structured KDL 2.0 syntax (strict KDL 2.0: booleans are #true/#false, strings may be bare identifiers or quoted/raw strings, and //, /* ... */, and /- comments are supported). Container children go inside { ... } blocks, and options are passed as positional arguments or named properties:

stack {
	choice 1 {
		t "--"
		seq {
			opt skip { t "-" }
			choice {
				n "a-z A-Z _ or non-ASCII"
				n escape
			}
		}
	}
	star {
		choice {
			n "a-z A-Z 0-9 _ - or non-ASCII"
			n escape
		}
	}
}

Container nodes:

Node Aliases Positional Args Properties Children
diagram Diagram Optional "simple" or "complex" type="simple"|"complex" 0+ (sole top-level node only)
complex-diagram ComplexDiagram (none) (none) 0+ (sole top-level node only)
sequence seq, and (none) (none) 1+
stack (none) (none) 1+
optional-sequence opt-seq (none) (none) 1+
alternating-sequence alt-seq (none) (none) Exactly 2
choice or Optional integer index (default 0) default=<int> or normal=<int> 1+
horizontal-choice h-choice (none) (none) 1+
multiple-choice m-choice Optional <int> and/or "any"|"all" default/normal=<int>, type="any"|"all" 1+
optional opt Optional "skip" or #true/#false skip=#true|#false|"skip" Exactly 1
one-or-more plus (none) (none) 1 or 2 (item, optional repeat)
zero-or-more star Optional "skip" or #true/#false skip=#true|#false|"skip" 1 or 2 (item, optional repeat)
group Optional label string label=<str> 1 (or 2 without label: item, label node)

Leaf nodes (must have no children):

Node Aliases Positional Args Properties
terminal t Required text string href=<str>, title=<str>, class or cls=<str>
non-terminal n Required text string href=<str>, title=<str>, class or cls=<str>
comment c Required text string href=<str>, title=<str>, class or cls=<str>
skip s (none) (none)
start Optional label string type="simple"|"complex", label=<str>
end Optional "simple" or "complex" type="simple"|"complex"
block (none) width, up, height, down (numbers), needs-space or needsSpace (bool)
style Required CSS string (none)

Unknown properties, conflicting positional + named options (such as choice 1 default=1), or specifying both cls and class raise a ParseError.

Example with leaf attributes and extended containers:

diagram type=complex {
	start type=complex label="expr"
	group "operands" {
		multiple-choice 1 all {
			terminal "a" href="#op-a" title="Literal a" class="hi"
			non-terminal "ident" href="#op-b"
		}
	}
	end complex
}

Auto-Detection

When syntax="auto" (the default for parse()), detectSyntax(source) inspects the first non-blank line:

  • Empty / whitespace-only input defaults to "dsl" (both parsers return an empty Diagram()).
  • Lines beginning with KDL syntax markers (//, /*, /-, (, ", #, {) are detected as "kdl".
  • Lines matching Command: or LeafCommand prelude: (with : followed by whitespace or end-of-line, and no quotes, braces, or = before :) are detected as "dsl".
  • Everything else (e.g. T "foo", T https://example.com, choice 0 { ... }, skip) is detected as "kdl".

Repository Layout

railroad-diagrams/
├── python/          # Python 3.12+ package (`import railroad`) and pytest suite
├── js/              # JavaScript ESM package (`railroad-diagrams`), CSS, TypeScript defs, and node:test suite
├── docs/            # Interactive generator, examples, and documentation images
├── pyproject.toml   # Python packaging, linting, and tablish release configuration
├── semver.txt       # Shared version source of truth for PyPI and npm
└── lint             # Local test and lint runner

Development & Releasing

Run all local checks (Python tests, linters, manifest check, and JS tests when node is installed):

./lint

Publishing to PyPI (via tablish)

Releases are managed with tablish. Running tablish bumps semver.txt, automatically syncs js/package.json to the same version, runs ./lint, builds and uploads the Python package to PyPI, commits the version bump, creates an annotated vX.Y.Z git tag, and pushes with --follow-tags:

tablish info               # inspect resolved publish settings
tablish bugfix --dry-run   # preview a patch release without uploading or committing
tablish bugfix             # publish patch release (or `feature` / `break` / explicit `X.Y.Z`)

Publishing to npm

  • Automated (recommended): Pushing a vX.Y.Z tag (which tablish does automatically) triggers .github/workflows/publish-npm.yml to verify versions, run the JS test suite, and publish js/ to npm. Configure npm Trusted Publishing for railroad-diagrams pointing at publish-npm.yml (or add an NPM_TOKEN repository secret).
  • Manual local publish: Run from js/:
cd js
npm install
npm test
npm pack --dry-run
npm publish --access public

Caveats

SVG can't actually respond to the sizes of content; in particular, there's no way to make SVG adjust sizing/positioning based on the length of some text. Instead, I guess at some font metrics, which mostly work as long as you're using a fairly standard monospace font. This works pretty well, but long text inside of a construct might eventually overflow the construct.

License

Standard MIT license; see LICENSE.

Don't ask me for permission to use any part of this project, just use it. I would appreciate attribution, but that is not required by the license. If you're doing something cool with it, again I'd appreciate it if you let me know, but that's not required either.

Explorer des projets similaires

Chargement…