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 a walk_railroad function to railroad.py (and slightly refactor the class hierarchy) #75

Closed lurch closed 4 years ago

lurch commented 4 years ago

Brief explanation: I've got a dict() of fairly complicated inter-related syntax diagrams, and they're now getting so complex I wanted to add some code to "sanity check" them. To do that, I need to iterate through all the nodes in each of the diagrams, and the new walk_railroad function allows me to do just that :smiley:

E.g. my current callback_fn looks something like:

def callback(item):
    if isinstance(item, NonTerminal):
        # ... do some checks ...
    elif isinstance(item, Terminal):
        # ... do some other checks ...

and then I can do:

for name, diagram in diagrams_dict.items():
    print("Checking {}".format(name))
    walk_railroad(diagram, callback)
tabatkins commented 4 years ago

Thanks, this was a useful addition!

I switched the design over to a .walk() method on the item, however; this allowed individual classes to override the method as they needed, such as OneOrMore which needs to walk over both its item and its repeat.

lurch commented 4 years ago

Thanks for the improvements, thanks for doing the JS port, and thanks for merging! :tada: (I'd missed the fact that OneOrMore's repeat was a node in its own right and not just a boolean flag)