# Copyright (c) 2003 Brian Sabbey # Hacks Copyright (c) 2003 John Plevyak import pydparser, sys, types, dl, os class Parser: def __init__(self, modules=None): self.file_prefix = "dparser_auto" self.parser = None self.dl_parser = None self.actions = [] if not modules: try: raise RuntimeError except RuntimeError: e,b,t = sys.exc_info() dicts = [t.tb_frame.f_back.f_globals] else: if type(modules) == list: dicts = [module.__dict__ for module in modules] else: dicts = modules functions = [val for dict in dicts for name, val in dict.items() if (isinstance(val, types.FunctionType)) and name[0:2] == 'd_'] functions.sort(lambda x, y: cmp(x.func_code.co_filename, y.func_code.co_filename) or cmp(x.func_code.co_firstlineno, y.func_code.co_firstlineno)) self.filename = self.file_prefix + ".g" g_file = open(self.filename, "w") for f in functions: g_file.write(f.__doc__) g_file.write(";\n${action}\n"); self.actions.append(f) g_file.close() def action(self, i, speculative, args): if speculative: return if i >= 0 and i < len(self.actions): f = self.actions[i] ac = f.func_code.co_argcount if ac == 1: return f(args) raise "where's the action?" + str(i) return None def parse(self, input): parser = self.parser filename = self.filename if not parser: if os.system("make_dparser " + filename): raise "make_dparser error" if os.system("cc -I/usr/local/include -shared -fPIC -o " + filename + ".so " + filename + ".d_parser.c") : raise "cc -static XX.d_parser.o error" self.dl_parser = dl.open("./" + filename + ".so") self.parser = self.dl_parser.sym("parser_tables_gram"); return pydparser.run_parser(self.parser, self.action, input)