Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from graphviz import Digraph
- def grammar_diagram(grammar):
- dot = Digraph('grammar')
- prods = grammar['productions']
- for k in prods.keys():
- dot.node(str(k))
- counter = 0
- for prod in prods.values():
- for branch in prod['branches']:
- token = branch['token']
- if token['type'] == 'Nonterminal':
- children = [token['data']]
- parent = prod['name']
- else:
- terminal = token['data']
- ty = terminal['type']
- if ty == 'Seq':
- children = [terminal['first'], terminal['second']]
- label = ';'
- elif ty == 'If':
- if terminal['else_'] is not None:
- children = [terminal['then_'], terminal['else_']]
- label = f'if {terminal["pred"]["type"]} then else'
- else:
- children = [terminal['then_']]
- label = f'if {terminal["pred"]["type"]}'
- elif ty == 'While':
- children = [terminal['body']]
- label = f'while {terminal["pred"]["type"]}'
- elif ty == 'Action':
- children = []
- label = terminal['action']['type']
- else:
- raise Exception('??')
- counter += 1
- name = f'dummy{counter}'
- dot.node(str(name), str(label))
- dot.edge(str(prod['name']), str(name))
- parent = name
- children = [c['data'] for c in children]
- for child in children:
- dot.edge(str(parent), str(child))
- return dot
- dot = grammar_diagram(best_grammar)
- dot.format = 'svg'
- dot.render()
- dot
RAW Paste Data