#!/usr/bin/env python
# -*- mode: python -*-

import sys
from ometa.runtime import ParseError
from ometa.grammar import OMeta
from ometa.builder import writePython
from ometa.vm_builder import writeBytecode, bytecodeToPython

if len(sys.argv) != 3:
 print "Usage: generate_grammar grammar-filename python-filename"
 sys.exit(1)


def findObject(name):
    classSplit = name.split('.')
    modname = '.'.join(classSplit[:-1])
    topLevel = __import__(modname)
    packages = modname.split(".")[1:]
    module = topLevel
    for p in packages:
        module = getattr(module, p)
    return getattr(module, classSplit[-1])

grammar = findObject(sys.argv[1])
pythonFile =  open(sys.argv[2], 'w')
g = OMeta(grammar)
tree = g.parseGrammar("Parser")
# source = writePython(tree)
bytecode = writeBytecode(tree)
source = bytecodeToPython(bytecode)
pythonFile.write("from ometa.runtime import OMetaBase as GrammarBase\n")
pythonFile.write(source)
