tabatkins / railroad-diagrams

:steam_locomotive: A small JS+SVG library for drawing railroad syntax diagrams, like on JSON.org. Now with a Python port!
MIT License
1.66k stars 153 forks source link

Add an expectation container #112

Closed LHLaurini closed 8 months ago

LHLaurini commented 8 months ago

As an example, take the following diagram for a simplified C-like string:

Diagram(
    "\"",
    ZeroOrMore(
        Choice(0,
            Sequence(
                "\\",
                Choice(1,
                    "n",
                    "\\",
                    "\""
                )
            ),
            NonTerminal("any printable character")
        )
    ),
    "\""
)

image

Suppose the input is "\p", and that choices should be matched in order, from top to bottom:

In this case, it is unclear whether a parser should backtrack and try the second branch (any printable character) or throw an error.

I believe an "expectation" container, where all items must match and no backtracking is allowed, would be useful.

LHLaurini commented 8 months ago

I suggest something like this: image

I'm willing to work on it myself, as long as I have everyone's approval.

EDIT: an alternative using the current set of components: image

tabatkins commented 8 months ago

Hm, is that sort of iconography reasonably well established elsewhere?

Happy to add something for this (it's very easy to add containers like that), just want to make sure it's doing something recognizable first.

LHLaurini commented 8 months ago

After searching for a while, I'm unable to find something similar on other diagrams. The closest I found is Boost Sprit's expectation operator.

As there doesn't seem to be any relevant standard, perhaps this would be best indicated by a comment instead of a new container?

I'm closing this for now until an existing example is found.