2020-04-22 19:29:27 -03:00
|
|
|
#!/usr/bin/env python3.8
|
|
|
|
|
|
|
|
""" Convert a grammar into a dot-file suitable for use with GraphViz
|
|
|
|
|
|
|
|
For example:
|
|
|
|
Generate the GraphViz file:
|
|
|
|
# scripts/grammar_grapher.py data/python.gram > python.gv
|
|
|
|
|
|
|
|
Then generate the graph...
|
|
|
|
|
|
|
|
# twopi python.gv -Tpng > python_twopi.png
|
|
|
|
|
|
|
|
or
|
|
|
|
|
|
|
|
# dot python.gv -Tpng > python_dot.png
|
|
|
|
|
|
|
|
NOTE: The _dot_ and _twopi_ tools seem to produce the most useful results.
|
|
|
|
The _circo_ tool is the worst of the bunch. Don't even bother.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
import sys
|
|
|
|
|
|
|
|
from typing import Any, List
|
|
|
|
|
|
|
|
sys.path.insert(0, ".")
|
|
|
|
|
|
|
|
from pegen.build import build_parser
|
|
|
|
from pegen.grammar import (
|
|
|
|
Alt,
|
|
|
|
Cut,
|
2022-03-06 10:26:28 -04:00
|
|
|
Forced,
|
2020-04-22 19:29:27 -03:00
|
|
|
Group,
|
|
|
|
Leaf,
|
|
|
|
Lookahead,
|
|
|
|
Rule,
|
|
|
|
NameLeaf,
|
|
|
|
NamedItem,
|
|
|
|
Opt,
|
|
|
|
Repeat,
|
|
|
|
Rhs,
|
|
|
|
)
|
|
|
|
|
2021-08-12 13:37:30 -03:00
|
|
|
argparser = argparse.ArgumentParser(
|
|
|
|
prog="graph_grammar",
|
|
|
|
description="Graph a grammar tree",
|
|
|
|
)
|
2020-06-06 01:21:40 -03:00
|
|
|
argparser.add_argument(
|
|
|
|
"-s",
|
|
|
|
"--start",
|
|
|
|
choices=["exec", "eval", "single"],
|
|
|
|
default="exec",
|
|
|
|
help="Choose the grammar's start rule (exec, eval or single)",
|
|
|
|
)
|
2020-04-22 19:29:27 -03:00
|
|
|
argparser.add_argument("grammar_file", help="The grammar file to graph")
|
|
|
|
|
|
|
|
|
|
|
|
def references_for_item(item: Any) -> List[Any]:
|
|
|
|
if isinstance(item, Alt):
|
|
|
|
return [_ref for _item in item.items for _ref in references_for_item(_item)]
|
|
|
|
elif isinstance(item, Cut):
|
|
|
|
return []
|
2022-03-06 10:26:28 -04:00
|
|
|
elif isinstance(item, Forced):
|
|
|
|
return references_for_item(item.node)
|
2020-04-22 19:29:27 -03:00
|
|
|
elif isinstance(item, Group):
|
|
|
|
return references_for_item(item.rhs)
|
|
|
|
elif isinstance(item, Lookahead):
|
|
|
|
return references_for_item(item.node)
|
|
|
|
elif isinstance(item, NamedItem):
|
|
|
|
return references_for_item(item.item)
|
|
|
|
|
|
|
|
# NOTE NameLeaf must be before Leaf
|
|
|
|
elif isinstance(item, NameLeaf):
|
|
|
|
if item.value == "ENDMARKER":
|
|
|
|
return []
|
|
|
|
return [item.value]
|
|
|
|
elif isinstance(item, Leaf):
|
|
|
|
return []
|
|
|
|
|
|
|
|
elif isinstance(item, Opt):
|
|
|
|
return references_for_item(item.node)
|
|
|
|
elif isinstance(item, Repeat):
|
|
|
|
return references_for_item(item.node)
|
|
|
|
elif isinstance(item, Rhs):
|
|
|
|
return [_ref for alt in item.alts for _ref in references_for_item(alt)]
|
|
|
|
elif isinstance(item, Rule):
|
|
|
|
return references_for_item(item.rhs)
|
|
|
|
else:
|
|
|
|
raise RuntimeError(f"Unknown item: {type(item)}")
|
|
|
|
|
|
|
|
|
|
|
|
def main() -> None:
|
|
|
|
args = argparser.parse_args()
|
|
|
|
|
|
|
|
try:
|
|
|
|
grammar, parser, tokenizer = build_parser(args.grammar_file)
|
|
|
|
except Exception as err:
|
|
|
|
print("ERROR: Failed to parse grammar file", file=sys.stderr)
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
references = {}
|
|
|
|
for name, rule in grammar.rules.items():
|
|
|
|
references[name] = set(references_for_item(rule))
|
|
|
|
|
|
|
|
# Flatten the start node if has only a single reference
|
2020-06-06 01:21:40 -03:00
|
|
|
root_node = {"exec": "file", "eval": "eval", "single": "interactive"}[args.start]
|
2020-04-22 19:29:27 -03:00
|
|
|
|
|
|
|
print("digraph g1 {")
|
|
|
|
print('\toverlap="scale";') # Force twopi to scale the graph to avoid overlaps
|
|
|
|
print(f'\troot="{root_node}";')
|
2020-06-06 01:21:40 -03:00
|
|
|
print(f"\t{root_node} [color=green, shape=circle];")
|
2020-04-22 19:29:27 -03:00
|
|
|
for name, refs in references.items():
|
2020-06-06 01:21:40 -03:00
|
|
|
for ref in refs:
|
|
|
|
print(f"\t{name} -> {ref};")
|
2020-04-22 19:29:27 -03:00
|
|
|
print("}")
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|