1#! /usr/bin/env python3 2 3# Read #define's and translate to Python code. 4# Handle #include statements. 5# Handle #define macros with one argument. 6# Anything that isn't recognized or doesn't translate into valid 7# Python is ignored. 8 9# Without filename arguments, acts as a filter. 10# If one or more filenames are given, output is written to corresponding 11# filenames in the local directory, translated to all uppercase, with 12# the extension replaced by ".py". 13 14# By passing one or more options of the form "-i regular_expression" 15# you can specify additional strings to be ignored. This is useful 16# e.g. to ignore casts to u_long: simply specify "-i '(u_long)'". 17 18# XXX To do: 19# - turn trailing C comments into Python comments 20# - turn C Boolean operators "&& || !" into Python "and or not" 21# - what to do about #if(def)? 22# - what to do about macros with multiple parameters? 23 24import sys, re, getopt, os 25 26p_define = re.compile(r'^[\t ]*#[\t ]*define[\t ]+([a-zA-Z0-9_]+)[\t ]+') 27 28p_macro = re.compile( 29 r'^[\t ]*#[\t ]*define[\t ]+' 30 r'([a-zA-Z0-9_]+)\(([_a-zA-Z][_a-zA-Z0-9]*)\)[\t ]+') 31 32p_include = re.compile(r'^[\t ]*#[\t ]*include[\t ]+<([^>\n]+)>') 33 34p_comment = re.compile(r'/\*([^*]+|\*+[^/])*(\*+/)?') 35p_cpp_comment = re.compile('//.*') 36 37ignores = [p_comment, p_cpp_comment] 38 39p_char = re.compile(r"'(\\.[^\\]*|[^\\])'") 40 41p_hex = re.compile(r"0x([0-9a-fA-F]+)L?") 42 43filedict = {} 44importable = {} 45 46try: 47 searchdirs=os.environ['include'].split(';') 48except KeyError: 49 try: 50 searchdirs=os.environ['INCLUDE'].split(';') 51 except KeyError: 52 searchdirs=['/usr/include'] 53 try: 54 searchdirs.insert(0, os.path.join('/usr/include', 55 os.environ['MULTIARCH'])) 56 except KeyError: 57 pass 58 59def main(): 60 global filedict 61 opts, args = getopt.getopt(sys.argv[1:], 'i:') 62 for o, a in opts: 63 if o == '-i': 64 ignores.append(re.compile(a)) 65 if not args: 66 args = ['-'] 67 for filename in args: 68 if filename == '-': 69 sys.stdout.write('# Generated by h2py from stdin\n') 70 process(sys.stdin, sys.stdout) 71 else: 72 with open(filename) as fp: 73 outfile = os.path.basename(filename) 74 i = outfile.rfind('.') 75 if i > 0: outfile = outfile[:i] 76 modname = outfile.upper() 77 outfile = modname + '.py' 78 with open(outfile, 'w') as outfp: 79 outfp.write('# Generated by h2py from %s\n' % filename) 80 filedict = {} 81 for dir in searchdirs: 82 if filename[:len(dir)] == dir: 83 filedict[filename[len(dir)+1:]] = None # no '/' trailing 84 importable[filename[len(dir)+1:]] = modname 85 break 86 process(fp, outfp) 87 88def pytify(body): 89 # replace ignored patterns by spaces 90 for p in ignores: 91 body = p.sub(' ', body) 92 # replace char literals by ord(...) 93 body = p_char.sub("ord('\\1')", body) 94 # Compute negative hexadecimal constants 95 start = 0 96 UMAX = 2*(sys.maxsize+1) 97 while 1: 98 m = p_hex.search(body, start) 99 if not m: break 100 s,e = m.span() 101 val = int(body[slice(*m.span(1))], 16) 102 if val > sys.maxsize: 103 val -= UMAX 104 body = body[:s] + "(" + str(val) + ")" + body[e:] 105 start = s + 1 106 return body 107 108def process(fp, outfp, env = {}): 109 lineno = 0 110 while 1: 111 line = fp.readline() 112 if not line: break 113 lineno = lineno + 1 114 match = p_define.match(line) 115 if match: 116 # gobble up continuation lines 117 while line[-2:] == '\\\n': 118 nextline = fp.readline() 119 if not nextline: break 120 lineno = lineno + 1 121 line = line + nextline 122 name = match.group(1) 123 body = line[match.end():] 124 body = pytify(body) 125 ok = 0 126 stmt = '%s = %s\n' % (name, body.strip()) 127 try: 128 exec(stmt, env) 129 except: 130 sys.stderr.write('Skipping: %s' % stmt) 131 else: 132 outfp.write(stmt) 133 match = p_macro.match(line) 134 if match: 135 macro, arg = match.group(1, 2) 136 body = line[match.end():] 137 body = pytify(body) 138 stmt = 'def %s(%s): return %s\n' % (macro, arg, body) 139 try: 140 exec(stmt, env) 141 except: 142 sys.stderr.write('Skipping: %s' % stmt) 143 else: 144 outfp.write(stmt) 145 match = p_include.match(line) 146 if match: 147 regs = match.regs 148 a, b = regs[1] 149 filename = line[a:b] 150 if filename in importable: 151 outfp.write('from %s import *\n' % importable[filename]) 152 elif filename not in filedict: 153 filedict[filename] = None 154 inclfp = None 155 for dir in searchdirs: 156 try: 157 inclfp = open(dir + '/' + filename) 158 break 159 except IOError: 160 pass 161 if inclfp: 162 with inclfp: 163 outfp.write( 164 '\n# Included from %s\n' % filename) 165 process(inclfp, outfp, env) 166 else: 167 sys.stderr.write('Warning - could not find file %s\n' % 168 filename) 169 170if __name__ == '__main__': 171 main() 172