Guest User

Untitled

a guest
Apr 30th, 2021
64
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from graphviz import Digraph
  2.  
  3. def grammar_diagram(grammar):
  4.     dot = Digraph('grammar')
  5.     prods = grammar['productions']
  6.     for k in prods.keys():
  7.         dot.node(str(k))
  8.     counter = 0
  9.     for prod in prods.values():
  10.         for branch in prod['branches']:
  11.             token = branch['token']
  12.            
  13.             if token['type'] == 'Nonterminal':
  14.                 children = [token['data']]    
  15.                 parent = prod['name']
  16.             else:
  17.                 terminal = token['data']
  18.                 ty = terminal['type']
  19.                 if ty == 'Seq':
  20.                     children = [terminal['first'], terminal['second']]
  21.                     label = ';'
  22.                 elif ty == 'If':
  23.                     if terminal['else_'] is not None:
  24.                         children = [terminal['then_'], terminal['else_']]
  25.                         label = f'if {terminal["pred"]["type"]} then else'
  26.                     else:
  27.                         children = [terminal['then_']]
  28.                         label = f'if {terminal["pred"]["type"]}'
  29.                 elif ty == 'While':
  30.                     children = [terminal['body']]
  31.                     label = f'while {terminal["pred"]["type"]}'
  32.                 elif ty == 'Action':
  33.                     children = []
  34.                     label = terminal['action']['type']
  35.                 else:
  36.                     raise Exception('??')
  37.                    
  38.                 counter += 1
  39.                 name = f'dummy{counter}'
  40.                 dot.node(str(name), str(label))
  41.                 dot.edge(str(prod['name']), str(name))
  42.                
  43.                 parent = name                
  44.                 children = [c['data'] for c in children]
  45.                
  46.             for child in children:
  47.                 dot.edge(str(parent), str(child))
  48.     return dot
  49.  
  50. dot = grammar_diagram(best_grammar)
  51. dot.format = 'svg'
  52. dot.render()
  53. dot
RAW Paste Data