1#!/usr/bin/env python3 2 3def to_enum_hd(k, prefix): 4 res = prefix 5 for c in k.upper(): 6 if c == ':' or c == '-': 7 res += '_' 8 continue 9 res += c 10 return res 11 12def build_header(headers): 13 res = {} 14 for k in headers: 15 size = len(k) 16 if size not in res: 17 res[size] = {} 18 ent = res[size] 19 c = k[-1] 20 if c not in ent: 21 ent[c] = [] 22 ent[c].append(k) 23 24 return res 25 26def gen_enum(tokens, prefix): 27 print('''\ 28enum {''') 29 for k in sorted(tokens): 30 print('''\ 31 {},'''.format(to_enum_hd(k, prefix))) 32 print('''\ 33 {}MAXIDX, 34}};'''.format(prefix)) 35 36def gen_index_header(tokens, prefix, value_type, comp_fun, return_type, fail_value): 37 print('''\ 38{} lookup_token(const {} *name, size_t namelen) {{ 39 switch (namelen) {{'''.format(return_type, value_type)) 40 b = build_header(tokens) 41 for size in sorted(b.keys()): 42 ents = b[size] 43 print('''\ 44 case {}:'''.format(size)) 45 print('''\ 46 switch (name[{}]) {{'''.format(size - 1)) 47 for c in sorted(ents.keys()): 48 headers = sorted(ents[c]) 49 print('''\ 50 case '{}':'''.format(c)) 51 for k in headers: 52 print('''\ 53 if ({}("{}", name, {})) {{ 54 return {}; 55 }}'''.format(comp_fun, k[:-1], size - 1, to_enum_hd(k, prefix))) 56 print('''\ 57 break;''') 58 print('''\ 59 } 60 break;''') 61 print('''\ 62 }} 63 return {}; 64}}'''.format(fail_value)) 65 66def gentokenlookup(tokens, prefix, value_type='uint8_t', comp_fun='util::streq_l', return_type='int', fail_value='-1'): 67 gen_enum(tokens, prefix) 68 print() 69 gen_index_header(tokens, prefix, value_type, comp_fun, return_type, fail_value) 70