tabatkins/railroad-diagrams
소개
:steam_locomotive: JSON.org와 같은 철도 문법 다이어그램을 그리는 소형 JS+SVG 라이브러리입니다. 이제 Python 포팅도 제공합니다!
디자인 및 미디어측정된 스타 증가
- in 24h
- 0
- in 7 days
- +1
- in 15 days
- +3
- in 1 month
- +4
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
README.md
OriginalRailroad-diagram Generator
╭──────────╮
├┼──────│ 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:
- JavaScript README (
js/, published on npm asrailroad-diagrams) - Python README (
python/, published on PyPI asrailroad-diagrams)
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
\tif 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 emptyDiagram()). - Lines beginning with KDL syntax markers (
//,/*,/-,(,",#,{) are detected as"kdl". - Lines matching
Command:orLeafCommand 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.Ztag (whichtablishdoes automatically) triggers .github/workflows/publish-npm.yml to verify versions, run the JS test suite, and publishjs/to npm. Configure npm Trusted Publishing forrailroad-diagramspointing atpublish-npm.yml(or add anNPM_TOKENrepository 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.
관련 프로젝트 살펴보기
불러오는 중…