#!/usr/bin/env python import sys #f = open("C:\\xxx.TXT", "w") #f.write(",".join(sys.argv)) #f.close() if sys.argv[1] == "-o": output_name = sys.argv[2] sys.stdout = open(output_name, "w") input_name = sys.argv[-1] # entry = [(input,new_state),(None,result)] numbered_states = {} states_sorted_by_number = [] root = [] numbered_states[id(root)] = 0 states_sorted_by_number.append(root) number = 1 def xget(needle, haystack): for input, result in haystack: if input == needle: return(result) return(None) def add_entry(name, value): global number r = root for c in name: n = xget(c, r) if n is None: n = [] numbered_states[id(n)] = number states_sorted_by_number.append(n) number += 1 r.append((c, n)) r = n assert(xget(None, r) is None) # no result set yet. assert(value is not None) r.append((None, value)) f = open(input_name, "r") raw_entries = {} for line in f.readlines(): name, value = line.split("\t", 1) if value.endswith("\n"): value = value[:-1] if name in raw_entries: print >>sys.stderr, "error: duplicate entry with key %r" % name sys.exit(1) raw_entries[name] = value add_entry(name, value) #print entries entry_size = max([len(state) for state in states_sorted_by_number]) print(""" struct State { unsigned int choice_count; unsigned char inputs[%d]; const char* result; unsigned int new_states[%d]; }; """ % (entry_size, entry_size)) print("static struct State state_table[] = {"); for i, state in enumerate(states_sorted_by_number): print("/*[%d] = */{" % i) print("\t/*.choice_count = */%d," % len(state)) print("\t/*.inputs = */{%s}," % ", ".join([str(ord(input)) if input is not None else "0" for input, result in state])) results = ['"%s"' % result for input, result in state if not isinstance(result, list)] assert(len(results) in [0,1]) print("\t/*.result = */%s," % (repr(results[0]).replace("'", '') if len(results) == 1 else "NULL")) sys.stdout.write("\t/*.new_states = */{") for input, result in state: if isinstance(result, list): result = numbered_states[id(result)] else: result = 0 sys.stdout.write("%d, " % result) print("}") print("},") print("};")