Repository navigation
Add railway diagrams #152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add railway diagrams #152
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| // Copyright 2026 TypeFox GmbH | ||
| // This program and the accompanying materials are made available under the | ||
| // terms of the MIT License, which is available in the project root. | ||
|
|
||
| package generator | ||
|
|
||
| import ( | ||
| "cmp" | ||
| "context" | ||
| "fmt" | ||
| "slices" | ||
| "strings" | ||
|
|
||
| "typefox.dev/fastbelt/internal/grammar" | ||
| ) | ||
|
|
||
| // RailroadDiagram is the rendered SVG railroad diagram of one grammar rule. | ||
| type RailroadDiagram struct { | ||
| Name string | ||
| SVG string | ||
| } | ||
|
|
||
| // GenerateRailroadDiagrams renders a standalone SVG railroad diagram for | ||
| // every parser, composite, and infix rule of grammr, in source order. | ||
| // Rule kinds with no meaningful concrete-syntax diagram (terminal/token | ||
| // rules) are omitted. | ||
| func GenerateRailroadDiagrams(grammr grammar.Grammar) []RailroadDiagram { | ||
| var rules []grammar.AbstractRule | ||
| for _, rule := range grammr.Rules() { | ||
| rules = append(rules, rule) | ||
| } | ||
| for _, rule := range grammr.Composites() { | ||
| rules = append(rules, rule) | ||
| } | ||
| for _, rule := range grammr.InfixRules() { | ||
| rules = append(rules, rule) | ||
| } | ||
| slices.SortFunc(rules, func(a, b grammar.AbstractRule) int { | ||
| return cmp.Compare(a.TextRange().Start, b.TextRange().Start) | ||
| }) | ||
|
|
||
| ctx := context.Background() | ||
| out := make([]RailroadDiagram, 0, len(rules)) | ||
| for _, rule := range rules { | ||
| if diagram, ok := grammar.BuildRuleDiagram(ctx, rule); ok { | ||
| out = append(out, RailroadDiagram{Name: rule.Name(), SVG: diagram.SVG()}) | ||
| } | ||
| } | ||
| return out | ||
| } | ||
|
|
||
| // GenerateRailroadIndexMarkdown renders a Markdown page linking every | ||
| // diagram (by relative <name>.svg file path) for convenient one-page | ||
| // browsing. | ||
| func GenerateRailroadIndexMarkdown(packageName string, diagrams []RailroadDiagram) string { | ||
| var b strings.Builder | ||
| fmt.Fprintf(&b, "# Railroad diagrams for %s\n\n", packageName) | ||
| for _, d := range diagrams { | ||
| fmt.Fprintf(&b, "## %s\n\n\n\n", d.Name, d.Name, d.Name) | ||
| } | ||
| return b.String() | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| // Copyright 2026 TypeFox GmbH | ||
| // This program and the accompanying materials are made available under the | ||
| // terms of the MIT License, which is available in the project root. | ||
|
|
||
| package generator | ||
|
|
||
| import ( | ||
| "encoding/xml" | ||
| "slices" | ||
| "strings" | ||
| "testing" | ||
|
|
||
| "typefox.dev/fastbelt/internal/grammar" | ||
| "typefox.dev/fastbelt/test" | ||
| ) | ||
|
|
||
| // Rule kinds are interleaved so source order differs from both alphabetical | ||
| // and grouped-by-kind order. | ||
| const railroadGeneratorFixtureGrammar = `grammar Test | ||
|
|
||
| interface Expr {} | ||
|
|
||
| interface BinaryExpression extends Expr { | ||
| Left Expr | ||
| Operator string | ||
| Right Expr | ||
| } | ||
|
|
||
| interface Foo { | ||
| Name string | ||
| Items []Item | ||
| } | ||
|
|
||
| interface Item { | ||
| Name string | ||
| } | ||
|
|
||
| entry Foo returns Foo: | ||
| "begin" Name=ID Items+=Item* | ||
|
|
||
| composite Combo: "prefix" Item; | ||
|
|
||
| infix BinaryExpression on Primary: | ||
| "+" | "-" | ||
|
|
||
| Item returns Item: | ||
| Name=ID | ||
|
|
||
| Primary returns Expr: | ||
| Value=NUMBER | ||
|
|
||
| token ID: /[a-zA-Z_][a-zA-Z0-9_]*/ | ||
| token NUMBER: /[0-9]+/ | ||
| ` | ||
|
|
||
| func TestGenerateRailroadDiagrams(t *testing.T) { | ||
| sc := grammar.CreateServices() | ||
| f := test.New(t, sc) | ||
| doc := f.Parse(railroadGeneratorFixtureGrammar) | ||
| doc.AssertNoParseErrors() | ||
|
|
||
| g, ok := doc.Root().(grammar.Grammar) | ||
| if !ok { | ||
| t.Fatalf("document root = %T, want grammar.Grammar", doc.Root()) | ||
| } | ||
| // Mirror the CLI, which desugars infix rules before running generators. | ||
| if err := grammar.ExpandInfixRules(g); err != nil { | ||
| t.Fatalf("ExpandInfixRules: %v", err) | ||
| } | ||
|
|
||
| diagrams := GenerateRailroadDiagrams(g) | ||
|
|
||
| names := make([]string, 0, len(diagrams)) | ||
| for _, d := range diagrams { | ||
| names = append(names, d.Name) | ||
| } | ||
| want := []string{"Foo", "Combo", "BinaryExpression", "Item", "Primary"} | ||
| if !slices.Equal(names, want) { | ||
| t.Fatalf("diagram names = %v, want %v (source order, no token rules)", names, want) | ||
| } | ||
|
|
||
| for _, d := range diagrams { | ||
| var root struct{ XMLName xml.Name } | ||
| if err := xml.Unmarshal([]byte(d.SVG), &root); err != nil { | ||
| t.Errorf("diagram for %q is not well-formed XML: %v\n%s", d.Name, err, d.SVG) | ||
| continue | ||
| } | ||
| if root.XMLName.Local != "svg" { | ||
| t.Errorf("diagram for %q has root element %q, want svg", d.Name, root.XMLName.Local) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| func TestGenerateRailroadIndexMarkdown(t *testing.T) { | ||
| md := GenerateRailroadIndexMarkdown("mylang", []RailroadDiagram{{Name: "Foo"}, {Name: "Item"}}) | ||
| for _, want := range []string{"# Railroad diagrams for mylang", "## Foo", "", "## Item", ""} { | ||
| if !strings.Contains(md, want) { | ||
| t.Errorf("index markdown missing %q, got:\n%s", want, md) | ||
| } | ||
| } | ||
| if strings.Index(md, "## Foo") > strings.Index(md, "## Item") { | ||
| t.Errorf("index markdown should keep the given diagram order, got:\n%s", md) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| // Copyright 2026 TypeFox GmbH | ||
| // This program and the accompanying materials are made available under the | ||
| // terms of the MIT License, which is available in the project root. | ||
|
|
||
| package grammar | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/base64" | ||
| "fmt" | ||
|
|
||
| core "typefox.dev/fastbelt" | ||
| "typefox.dev/fastbelt/server" | ||
| "typefox.dev/fastbelt/util/service" | ||
| "typefox.dev/lsp" | ||
| ) | ||
|
|
||
| type hoverProviderImpl struct { | ||
| sc *service.Container | ||
| } | ||
|
|
||
| // NewHoverProvider returns the grammar language's [server.HoverProvider]: | ||
| // the same documentation-comment content as [server.DefaultHoverProvider], | ||
| // plus - for grammar rule nodes - a railroad syntax diagram of the rule's | ||
| // concrete syntax. | ||
| func NewHoverProvider(sc *service.Container) server.HoverProvider { | ||
| return &hoverProviderImpl{sc: sc} | ||
| } | ||
|
|
||
| func (p *hoverProviderImpl) HandleHoverRequest(ctx context.Context, params *lsp.HoverParams) (*lsp.Hover, error) { | ||
| target, sourceRange := server.TargetAtCursor(ctx, p.sc, ¶ms.TextDocumentPositionParams) | ||
| if target == nil { | ||
| return nil, nil | ||
| } | ||
|
|
||
| content := "" | ||
| if docProvider, err := service.Get[server.DocumentationProvider](p.sc); err == nil { | ||
| content = docProvider.Documentation(target) | ||
| } | ||
| if diagram := diagramMarkdown(ctx, target); diagram != "" { | ||
| if content != "" { | ||
| content += "\n\n---\n\n" | ||
| } | ||
| content += diagram | ||
| } | ||
| if content == "" { | ||
| return nil, nil | ||
| } | ||
|
|
||
| return &lsp.Hover{ | ||
| Contents: lsp.MarkupContent{ | ||
| Kind: lsp.Markdown, | ||
| Value: content, | ||
| }, | ||
| Range: sourceRange, | ||
| }, nil | ||
| } | ||
|
|
||
| // diagramMarkdown returns a Markdown image embedding a base64-encoded SVG | ||
| // railroad diagram for node, or "" if node isn't a grammar rule with a | ||
| // meaningful concrete-syntax diagram (e.g. a terminal/token rule). | ||
| func diagramMarkdown(ctx context.Context, node core.AstNode) string { | ||
| rule, ok := node.(AbstractRule) | ||
| if !ok { | ||
| return "" | ||
| } | ||
| diagram, ok := BuildRuleDiagram(ctx, rule) | ||
| if !ok { | ||
| return "" | ||
| } | ||
| encoded := base64.StdEncoding.EncodeToString([]byte(diagram.SVG())) | ||
| return fmt.Sprintf("", encoded) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.