From ed895b424295041af16752f9b8fe030faecff72d Mon Sep 17 00:00:00 2001 From: Quint Daenen Date: Tue, 9 Apr 2024 08:27:10 +0200 Subject: [PATCH] Initial commit. --- .github/workflows/test.yml | 10 ++ LICENSE | 201 ++++++++++++++++++++++++++++++ Makefile | 13 ++ README.md | 23 ++++ go.mod | 3 + internal/svg/box.go | 42 +++++++ internal/svg/box_test.go | 23 ++++ internal/svg/bypass.go | 39 ++++++ internal/svg/curve.go | 53 ++++++++ internal/svg/line.go | 77 ++++++++++++ internal/svg/settings.go | 34 +++++ internal/svg/svg.go | 23 ++++ internal/svg/svg_test.go | 100 +++++++++++++++ internal/svg/terminator.go | 41 ++++++ internal/svg/testdata/curve0.svg | 6 + internal/svg/testdata/curve1.svg | 6 + internal/svg/testdata/lines1.svg | 81 ++++++++++++ internal/svg/testdata/lines10.svg | 81 ++++++++++++ internal/svg/testdata/total.svg | 61 +++++++++ internal/svg/text.go | 34 +++++ railroad.go | 87 +++++++++++++ railroad_test.go | 59 +++++++++ testdata/example1.svg | 25 ++++ testdata/explain-and.svg | 14 +++ testdata/explain-optional.svg | 18 +++ 25 files changed, 1154 insertions(+) create mode 100644 .github/workflows/test.yml create mode 100755 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 go.mod create mode 100644 internal/svg/box.go create mode 100644 internal/svg/box_test.go create mode 100644 internal/svg/bypass.go create mode 100644 internal/svg/curve.go create mode 100644 internal/svg/line.go create mode 100644 internal/svg/settings.go create mode 100644 internal/svg/svg.go create mode 100644 internal/svg/svg_test.go create mode 100644 internal/svg/terminator.go create mode 100644 internal/svg/testdata/curve0.svg create mode 100644 internal/svg/testdata/curve1.svg create mode 100644 internal/svg/testdata/lines1.svg create mode 100644 internal/svg/testdata/lines10.svg create mode 100644 internal/svg/testdata/total.svg create mode 100644 internal/svg/text.go create mode 100644 railroad.go create mode 100644 railroad_test.go create mode 100644 testdata/example1.svg create mode 100755 testdata/explain-and.svg create mode 100755 testdata/explain-optional.svg diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..89843a0 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,10 @@ +on: push +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v4 + with: + go-version: '1.22.2' + - run: make test diff --git a/LICENSE b/LICENSE new file mode 100755 index 0000000..75c0033 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2024 0x51 BV + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e18a1b1 --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +.PHONY: test fmt + +test: + go test -v -cover ./... + +gen: + GENERATE_SVG=true go test ./... + +fmt: + go mod tidy + gofmt -s -w . + goarrange run -r . + golangci-lint run ./... diff --git a/README.md b/README.md new file mode 100644 index 0000000..b3bacb2 --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# Railroad Diagrams + +## How to Read + +You read the diagram from left to right and from top to bottom. The diagram is a visual representation of a context-free +grammar. The diagram shows the rules of the grammar and how they are connected. + +The following conventions are used: + +- The following diagram shows values `A`, `B` and `C`, which must be specified. The required values are defined on the + main line of the diagram. (_ABNF_: `and = A B C`) + ![explain-and](./testdata/explain-and.svg) +- The following diagram shows the optional value `A`. The value can be bypassed by following the empty path. + (_ABNF_: `opt = [A] B `) + ![explain-optional](./testdata/explain-optional.svg) + +## Example + +![example-svg](./testdata/example1.svg) + +## References + +- [Niklaus Wirth](https://www.research-collection.ethz.ch/bitstream/handle/20.500.11850/68910/eth-3059-01.pdf) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..353087b --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/0x51-dev/railroad + +go 1.22.2 diff --git a/internal/svg/box.go b/internal/svg/box.go new file mode 100644 index 0000000..b3f4623 --- /dev/null +++ b/internal/svg/box.go @@ -0,0 +1,42 @@ +package svg + +type Point struct { + X, Y float64 +} + +type Box struct { + Position Point + Size Point +} + +func NewBox(position Point, size Point) Box { + if size.X < 0 { + position.X += size.X + size.X = -size.X + } + if size.Y < 0 { + position.Y += size.Y + size.Y = -size.Y + } + return Box{ + Position: position, + Size: size, + } +} +func (b Box) Combine(a Box) Box { + if a.Position.X < b.Position.X { + b.Size.X += b.Position.X - a.Position.X + b.Position.X = a.Position.X + } + if a.Position.Y < b.Position.Y { + b.Size.Y += b.Position.Y - a.Position.Y + b.Position.Y = a.Position.Y + } + if a.Position.X+a.Size.X > b.Position.X+b.Size.X { + b.Size.X = a.Position.X + a.Size.X - b.Position.X + } + if a.Position.Y+a.Size.Y > b.Position.Y+b.Size.Y { + b.Size.Y = a.Position.Y + a.Size.Y - b.Position.Y + } + return b +} diff --git a/internal/svg/box_test.go b/internal/svg/box_test.go new file mode 100644 index 0000000..83bb679 --- /dev/null +++ b/internal/svg/box_test.go @@ -0,0 +1,23 @@ +package svg + +import "testing" + +func TestBox_Combine(t *testing.T) { + t.Run("empty", func(t *testing.T) { + var box Box + other := Box{ + Size: Point{X: 3, Y: 4}, + } + if box.Combine(other) != other { + t.Errorf("Expected %v, but got %v", other, box) + } + }) + t.Run("gap", func(t *testing.T) { + box := Box{Position: Point{X: 1, Y: 2}, Size: Point{X: 3, Y: 4}} + other := Box{Position: Point{X: 5, Y: 6}, Size: Point{X: 7, Y: 8}} + expected := Box{Position: Point{X: 1, Y: 2}, Size: Point{X: 11, Y: 12}} + if result := box.Combine(other); result != expected { + t.Errorf("Expected %v, but got %v", expected, result) + } + }) +} diff --git a/internal/svg/bypass.go b/internal/svg/bypass.go new file mode 100644 index 0000000..3676aad --- /dev/null +++ b/internal/svg/bypass.go @@ -0,0 +1,39 @@ +package svg + +import "fmt" + +type Bypass struct { + Element SVGable +} + +func (b Bypass) SVG(start Point) (string, Point, Box) { + wrappedStart := Point{X: start.X + curveRadius*2, Y: start.Y} + wrappedSVG, wrappedEnd, wrappedBox := b.Element.SVG(wrappedStart) + + l := wrappedBox.Size.Y + (wrappedBox.Position.Y - start.Y) - curveRadius + + curveStartSVG, curveStart, curveStartBox := CurveInvS{L: l}.SVG(start) + curveEndSVG, curveEnd, curveEndBox := CurveS{ + L: curveStart.Y - wrappedEnd.Y - 2*curveRadius, + }.SVG(Point{ + X: curveStart.X + wrappedBox.Size.X, + Y: curveStart.Y, + }) + return fmt.Sprintf( + ` + +%s + +%s + +%s +`, + start.X, start.Y, wrappedStart.X, wrappedStart.Y, + wrappedSVG, + wrappedEnd.X, wrappedEnd.Y, curveEnd.X, curveEnd.Y, + + curveStartSVG, + curveStart.X, curveStart.Y, curveStart.X+wrappedBox.Size.X, curveStart.Y, + curveEndSVG, + ), curveEnd, curveStartBox.Combine(wrappedBox).Combine(curveEndBox) +} diff --git a/internal/svg/curve.go b/internal/svg/curve.go new file mode 100644 index 0000000..538c889 --- /dev/null +++ b/internal/svg/curve.go @@ -0,0 +1,53 @@ +package svg + +import "fmt" + +type CurveInvS struct { + L float64 +} + +func (c CurveInvS) SVG(start Point) (string, Point, Box) { + r, ry, x, y, l := curveRadius, curveRadius, start.X, start.Y, c.L + return fmt.Sprintf( + ``, + x, y, + + x+r, y, + x+r, y+ry, + + x+r, y+ry+l, + + x+r, y+2*ry+l, + x+2*r, y+2*ry+l, + + strokeWidth, + ), Point{X: x + 2*r, Y: y + 2*ry + l}, Box{ + Position: Point{X: x, Y: y}, + Size: Point{X: 2 * r, Y: 2*ry + l}, + } +} + +type CurveS struct { + L float64 +} + +func (c CurveS) SVG(start Point) (string, Point, Box) { + r, ry, x, y, l, ly := curveRadius, -curveRadius, start.X, start.Y, -c.L, c.L + return fmt.Sprintf( + ``, + x, y, + + x+r, y, + x+r, y+ry, + + x+r, y+ry+l, + + x+r, y+2*ry+l, + x+2*r, y+2*ry+l, + + strokeWidth, + ), Point{X: x + 2*r, Y: y + 2*ry + l}, Box{ + Position: Point{X: x, Y: y + 2*ry + l}, + Size: Point{X: 2 * r, Y: 2*r + ly}, + } +} diff --git a/internal/svg/line.go b/internal/svg/line.go new file mode 100644 index 0000000..c8c29c6 --- /dev/null +++ b/internal/svg/line.go @@ -0,0 +1,77 @@ +package svg + +import "fmt" + +type Line struct { + RelativeEnd Point +} + +func (e Line) SVG(start Point) (string, Point, Box) { + end, box := Point{X: start.X + e.RelativeEnd.X, Y: start.Y + e.RelativeEnd.Y}, NewBox(start, e.RelativeEnd) + next := end + + // The line is horizontal/vertical. + if e.RelativeEnd.X == 0 || e.RelativeEnd.Y == 0 { + return fmt.Sprintf( + ``, + start.X, start.Y, + start.X+e.RelativeEnd.X, start.Y+e.RelativeEnd.Y, + ), next, box + } + + crX, crY := curveRadius, curveRadius + if -2*curveRadius < e.RelativeEnd.X && e.RelativeEnd.X < 2*curveRadius { + crX = 0 + } + if -2*curveRadius < e.RelativeEnd.Y && e.RelativeEnd.Y < 2*curveRadius { + crY = 0 + } + + switch { + // -> NW + case e.RelativeEnd.X < 0 && e.RelativeEnd.Y < 0: + start, end = end, start + e.RelativeEnd.X = -e.RelativeEnd.X + e.RelativeEnd.Y = -e.RelativeEnd.Y + fallthrough + // -> SE + case 0 < e.RelativeEnd.X && 0 < e.RelativeEnd.Y: + return fmt.Sprintf( + ``, + start.X, start.Y, // Start top-left. + + start.X+crY, start.Y, // Curve down. + start.X+crY, start.Y+crY, + + start.X+crY, start.Y+e.RelativeEnd.Y-crX, // Straight down. + + start.X+crY, end.Y, // Curve right. + start.X+crY+crX, end.Y, + + end.X, end.Y, // End bottom-right. + ), next, box + // -> SW + case e.RelativeEnd.X < 0 && 0 < e.RelativeEnd.Y: + start, end = end, start + e.RelativeEnd.X = -e.RelativeEnd.X + e.RelativeEnd.Y = -e.RelativeEnd.Y + fallthrough + // -> NE + case 0 < e.RelativeEnd.X && e.RelativeEnd.Y < 0: + return fmt.Sprintf( + ``, + start.X, start.Y, // Start bottom-left. + + start.X+crX, start.Y, // Curve up. + start.X+crX, start.Y-crX, + + start.X+crX, start.Y+e.RelativeEnd.Y+crY, // Straight up. + + start.X+crY, start.Y+e.RelativeEnd.Y, // Curve right. + start.X+2*crY, start.Y+e.RelativeEnd.Y, + + end.X, end.Y, // End top-right. + ), next, box + } + return ``, next, box +} diff --git a/internal/svg/settings.go b/internal/svg/settings.go new file mode 100644 index 0000000..c0c9144 --- /dev/null +++ b/internal/svg/settings.go @@ -0,0 +1,34 @@ +package svg + +var ( + fontSize = 8.0 + pointRadius = 1.0 + interNodeSpace = 10.0 + curveRadius = 5.0 + strokeWidth = 1.0 +) + +// SetFontSize sets the font size of the text. +func SetFontSize(size float64) { + fontSize = size +} + +// SetPointRadius sets the pointRadius of a point. +func SetPointRadius(r float64) { + pointRadius = r +} + +// SetInterNodeSpace sets the interNodeSpace of the nodes. +func SetInterNodeSpace(s float64) { + interNodeSpace = s +} + +// SetCurveRadius sets the curveRadius of the curve. +func SetCurveRadius(r float64) { + curveRadius = r +} + +// SetStrokeWidth sets the stroke width of the curve. +func SetStrokeWidth(w float64) { + strokeWidth = w +} diff --git a/internal/svg/svg.go b/internal/svg/svg.go new file mode 100644 index 0000000..2de4d7f --- /dev/null +++ b/internal/svg/svg.go @@ -0,0 +1,23 @@ +package svg + +import "fmt" + +type SVGable interface { + SVG(start Point) (svg string, end Point, box Box) +} + +func DebugSVG(element SVGable, start Point) (string, Point, Box) { + svgElement, end, box := element.SVG(start) + return fmt.Sprintf( + ` + +%s + + +`, + start.X, start.Y, + svgElement, + end.X, end.Y, + box.Position.X, box.Position.Y, box.Size.X, box.Size.Y, + ), end, box +} diff --git a/internal/svg/svg_test.go b/internal/svg/svg_test.go new file mode 100644 index 0000000..cb9ec96 --- /dev/null +++ b/internal/svg/svg_test.go @@ -0,0 +1,100 @@ +package svg + +import ( + "fmt" + "os" + "testing" +) + +func TestCurve(t *testing.T) { + if os.Getenv("GENERATE_SVG") != "" { + for idx, e := range []struct { + element SVGable + start Point + }{ + {CurveS{L: 10}, Point{X: 10, Y: 30}}, + {CurveInvS{L: 10}, Point{X: 10, Y: 10}}, + } { + svg, _, box := DebugSVG(e.element, e.start) + _ = os.WriteFile(fmt.Sprintf("testdata/curve%d.svg", idx), []byte( + fmt.Sprintf( + `%s`, + box.Size.X+20, box.Size.Y+20, svg, + ), + ), 0644) + } + + t.Run("lines", func(t *testing.T) { + for _, size := range []float64{1, 10} { + var combinedSVG string + start := Point{X: 0, Y: 0} + combinedBox := Box{Position: start} + for _, e := range []SVGable{ + Line{RelativeEnd: Point{Y: -10 * size}}, + Line{RelativeEnd: Point{X: 2 * size, Y: -5 * size}}, + Line{RelativeEnd: Point{X: 5 * size, Y: -5 * size}}, + Line{RelativeEnd: Point{X: 5 * size, Y: -2 * size}}, + Line{RelativeEnd: Point{X: 10 * size}}, + Line{RelativeEnd: Point{X: 5 * size, Y: 2 * size}}, + Line{RelativeEnd: Point{X: 5 * size, Y: 5 * size}}, + Line{RelativeEnd: Point{X: 2 * size, Y: 5 * size}}, + Line{RelativeEnd: Point{Y: 10 * size}}, + Line{RelativeEnd: Point{X: -2 * size, Y: 5 * size}}, + Line{RelativeEnd: Point{X: -5 * size, Y: 5 * size}}, + Line{RelativeEnd: Point{X: -5 * size, Y: 2 * size}}, + Line{RelativeEnd: Point{X: -10 * size}}, + Line{RelativeEnd: Point{X: -5 * size, Y: -2 * size}}, + Line{RelativeEnd: Point{X: -5 * size, Y: -5 * size}}, + Line{RelativeEnd: Point{X: -2 * size, Y: -5 * size}}, + } { + svg, end, box := DebugSVG(e, start) + // svg, end, box := e.SVG(start) + combinedSVG += svg + start = end + combinedBox = combinedBox.Combine(box) + } + _ = os.WriteFile(fmt.Sprintf("testdata/lines%.0f.svg", size), []byte( + fmt.Sprintf( + `%s`, + combinedBox.Position.X-10, combinedBox.Position.Y-10, + combinedBox.Size.X+20, combinedBox.Size.Y+20, + combinedSVG, + ), + ), 0644) + } + }) + + t.Run("combined", func(t *testing.T) { + var combinedSVG string + start := Point{X: 0, Y: 0} + combinedBox := Box{Position: start} + for _, e := range []SVGable{ + Start{}, + CurveS{L: 10}, + Line{RelativeEnd: Point{X: 10, Y: 10}}, + Bypass{ + Element: TextBox{Text: "Hello,"}, + }, + Line{RelativeEnd: Point{X: 10, Y: -10}}, + TextBox{Text: "World!", RoundedBorders: true}, + Line{RelativeEnd: Point{X: 10}}, + CurveInvS{L: 10}, + End{}, + } { + svg, end, box := DebugSVG(e, start) + // svg, end, box := e.SVG(start) + combinedSVG += svg + start = end + combinedBox = combinedBox.Combine(box) + } + _ = os.WriteFile("testdata/total.svg", []byte( + fmt.Sprintf( + `%s`, + combinedBox.Position.X-10, combinedBox.Position.Y-10, + combinedBox.Size.X+20, combinedBox.Size.Y+20, + combinedSVG, + ), + ), 0644) + }) + } +} diff --git a/internal/svg/terminator.go b/internal/svg/terminator.go new file mode 100644 index 0000000..81ba59a --- /dev/null +++ b/internal/svg/terminator.go @@ -0,0 +1,41 @@ +package svg + +import ( + "fmt" +) + +// Start is a terminator that starts a path, i.e. "o-". +type Start struct{} + +func (Start) SVG(start Point) (string, Point, Box) { + return fmt.Sprintf( + ` +`, + start.X, start.Y, // circle + pointRadius, + + start.X+pointRadius/2, start.Y, // line + start.X+pointRadius/2+interNodeSpace, start.Y, + ), Point{X: start.X + interNodeSpace, Y: start.Y}, Box{ + Position: Point{X: start.X - pointRadius, Y: start.Y - pointRadius}, + Size: Point{X: pointRadius + interNodeSpace, Y: pointRadius * 2}, + } +} + +// End is a terminator that ends a path, i.e. "-o". +type End struct{} + +func (End) SVG(start Point) (string, Point, Box) { + return fmt.Sprintf( + ` +`, + start.X, start.Y, // line + start.X+interNodeSpace, start.Y, + + start.X+interNodeSpace, start.Y, // circle + pointRadius, + ), Point{X: start.X + interNodeSpace, Y: start.Y}, Box{ + Position: Point{X: start.X, Y: start.Y - pointRadius}, + Size: Point{X: interNodeSpace + pointRadius, Y: pointRadius * 2}, + } +} diff --git a/internal/svg/testdata/curve0.svg b/internal/svg/testdata/curve0.svg new file mode 100644 index 0000000..319f9c5 --- /dev/null +++ b/internal/svg/testdata/curve0.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/internal/svg/testdata/curve1.svg b/internal/svg/testdata/curve1.svg new file mode 100644 index 0000000..c1f1181 --- /dev/null +++ b/internal/svg/testdata/curve1.svg @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/internal/svg/testdata/lines1.svg b/internal/svg/testdata/lines1.svg new file mode 100644 index 0000000..2811855 --- /dev/null +++ b/internal/svg/testdata/lines1.svg @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/internal/svg/testdata/lines10.svg b/internal/svg/testdata/lines10.svg new file mode 100644 index 0000000..bc8e94b --- /dev/null +++ b/internal/svg/testdata/lines10.svg @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/internal/svg/testdata/total.svg b/internal/svg/testdata/total.svg new file mode 100644 index 0000000..aecf55d --- /dev/null +++ b/internal/svg/testdata/total.svg @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + +Hello, + + + + + + + + + + + + + + + + + +World! + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/internal/svg/text.go b/internal/svg/text.go new file mode 100644 index 0000000..120ca37 --- /dev/null +++ b/internal/svg/text.go @@ -0,0 +1,34 @@ +package svg + +import "fmt" + +type TextBox struct { + Text string + RoundedBorders bool +} + +func (t TextBox) SVG(start Point) (string, Point, Box) { + offset := 10.0 + textWidth := fontSize / 2 + rounding := 1.0 + if t.RoundedBorders { + rounding = textWidth + } + textLength := float64(len(t.Text)) * textWidth + return fmt.Sprintf( + ` + +%s +`, + start.X, start.Y-textWidth-offset/2, + rounding, rounding, + textLength+offset, fontSize+offset, + + start.X+textLength/2+offset/2, start.Y, + fontSize, textLength, + t.Text, + ), Point{X: start.X + textLength + offset, Y: start.Y}, Box{ + Position: Point{X: start.X, Y: start.Y - textWidth - offset/2}, + Size: Point{X: textLength + offset, Y: fontSize + offset}, + } +} diff --git a/railroad.go b/railroad.go new file mode 100644 index 0000000..053cc81 --- /dev/null +++ b/railroad.go @@ -0,0 +1,87 @@ +package railroad + +import ( + "fmt" + "github.com/0x51-dev/railroad/internal/svg" +) + +func GenerateSVG(r Rule) string { + margin := 10.0 + ruleSVG, _, box := r.SVG(svg.Point{}) + return fmt.Sprintf( + ` +%s +`, + box.Position.X-margin, box.Position.Y-margin, + box.Size.X+2*margin, box.Size.Y+2*margin, + ruleSVG, + ) +} + +type AndExpression struct { + Expr []Expression +} + +func (AndExpression) expression() {} + +func (a AndExpression) SVG(start svg.Point) (string, svg.Point, svg.Box) { + var combinedSVG string + startBox := svg.Box{Position: start} + for idx, e := range a.Expr { + exprSVG, exprEnd, exprBox := e.SVG(start) + combinedSVG += exprSVG + start = exprEnd + startBox = startBox.Combine(exprBox) + if idx < len(a.Expr)-1 { + combinedSVG += fmt.Sprintf( + ``, + start.X, start.Y, start.X+10, start.Y, + ) + start.X += 10 + } + } + return fmt.Sprintf(`%s`, combinedSVG), start, startBox +} + +type Expression interface { + svg.SVGable + + expression() +} + +type OptionalExpression struct { + Expr Expression +} + +func (OptionalExpression) expression() {} + +func (o OptionalExpression) SVG(start svg.Point) (string, svg.Point, svg.Box) { + return svg.Bypass{Element: o.Expr}.SVG(start) +} + +type Rule struct { + Name string + Expr Expression +} + +func (r Rule) SVG(start svg.Point) (string, svg.Point, svg.Box) { + startSVG, startEnd, startBox := svg.Start{}.SVG(start) + ruleSVG, ruleEnd, ruleBox := r.Expr.SVG(startEnd) + endSVG, endEnd, endBox := svg.End{}.SVG(ruleEnd) + return fmt.Sprintf(`%s%s%s`, r.Name, startSVG, ruleSVG, endSVG), endEnd, startBox.Combine(ruleBox).Combine(endBox) +} + +type Term struct { + Value string +} + +func T(value string) Term { + return Term{Value: value} +} + +func (Term) expression() {} + +func (t Term) SVG(start svg.Point) (string, svg.Point, svg.Box) { + termSVG, termEnd, termBox := svg.TextBox{Text: t.Value}.SVG(start) + return fmt.Sprintf(`%s`, termSVG), termEnd, termBox +} diff --git a/railroad_test.go b/railroad_test.go new file mode 100644 index 0000000..5c0149f --- /dev/null +++ b/railroad_test.go @@ -0,0 +1,59 @@ +package railroad_test + +import ( + "github.com/0x51-dev/railroad" + "os" + "testing" +) + +func TestRailroad(t *testing.T) { + for _, r := range []railroad.Rule{ + { + Name: "explain-and", + Expr: railroad.AndExpression{ + Expr: []railroad.Expression{ + railroad.T("A"), + railroad.T("B"), + railroad.T("C"), + }, + }, + }, + { + Name: "explain-optional", + Expr: railroad.AndExpression{ + Expr: []railroad.Expression{ + railroad.OptionalExpression{ + Expr: railroad.T("A"), + }, + railroad.T("B"), + }, + }, + }, + + { + Name: "example1", + Expr: railroad.OptionalExpression{ + Expr: railroad.AndExpression{ + Expr: []railroad.Expression{ + railroad.OptionalExpression{ + Expr: railroad.T("Hello,"), + }, + railroad.T("World!"), + }, + }, + }, + }, + } { + t.Run(r.Name, func(t *testing.T) { + f, err := os.OpenFile("testdata/"+r.Name+".svg", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755) + if err != nil { + t.Fatal(err) + } + + _, err = f.WriteString(railroad.GenerateSVG(r)) + if err != nil { + t.Fatal(err) + } + }) + } +} diff --git a/testdata/example1.svg b/testdata/example1.svg new file mode 100644 index 0000000..96aa91e --- /dev/null +++ b/testdata/example1.svg @@ -0,0 +1,25 @@ + + + + + + + + +Hello, + + + + + + + +World! + + + + + + + + \ No newline at end of file diff --git a/testdata/explain-and.svg b/testdata/explain-and.svg new file mode 100755 index 0000000..75c3c18 --- /dev/null +++ b/testdata/explain-and.svg @@ -0,0 +1,14 @@ + + + + +A + + +B + + +C + + + \ No newline at end of file diff --git a/testdata/explain-optional.svg b/testdata/explain-optional.svg new file mode 100755 index 0000000..165aca1 --- /dev/null +++ b/testdata/explain-optional.svg @@ -0,0 +1,18 @@ + + + + + + +A + + + + + + + +B + + + \ No newline at end of file