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 fp = open(filename, 'r') 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 outfp = open(outfile, 'w') 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 outfp.close() 88 fp.close() 89 90def pytify(body): 91 # replace ignored patterns by spaces 92 for p in ignores: 93 body = p.sub(' ', body) 94 # replace char literals by ord(...) 95 body = p_char.sub("ord('\\1')", body) 96 # Compute negative hexadecimal constants 97 start = 0 98 UMAX = 2*(sys.maxsize+1) 99 while 1: 100 m = p_hex.search(body, start) 101 if not m: break 102 s,e = m.span() 103 val = int(body[slice(*m.span(1))], 16) 104 if val > sys.maxsize: 105 val -= UMAX 106 body = body[:s] + "(" + str(val) + ")" + body[e:] 107 start = s + 1 108 return body 109 110def process(fp, outfp, env = {}): 111 lineno = 0 112 while 1: 113 line = fp.readline() 114 if not line: break 115 lineno = lineno + 1 116 match = p_define.match(line) 117 if match: 118 # gobble up continuation lines 119 while line[-2:] == '\\\n': 120 nextline = fp.readline() 121 if not nextline: break 122 lineno = lineno + 1 123 line = line + nextline 124 name = match.group(1) 125 body = line[match.end():] 126 body = pytify(body) 127 ok = 0 128 stmt = '%s = %s\n' % (name, body.strip()) 129 try: 130 exec(stmt, env) 131 except: 132 sys.stderr.write('Skipping: %s' % stmt) 133 else: 134 outfp.write(stmt) 135 match = p_macro.match(line) 136 if match: 137 macro, arg = match.group(1, 2) 138 body = line[match.end():] 139 body = pytify(body) 140 stmt = 'def %s(%s): return %s\n' % (macro, arg, body) 141 try: 142 exec(stmt, env) 143 except: 144 sys.stderr.write('Skipping: %s' % stmt) 145 else: 146 outfp.write(stmt) 147 match = p_include.match(line) 148 if match: 149 regs = match.regs 150 a, b = regs[1] 151 filename = line[a:b] 152 if filename in importable: 153 outfp.write('from %s import *\n' % importable[filename]) 154 elif filename not in filedict: 155 filedict[filename] = None 156 inclfp = None 157 for dir in searchdirs: 158 try: 159 inclfp = open(dir + '/' + filename) 160 break 161 except IOError: 162 pass 163 if inclfp: 164 outfp.write( 165 '\n# Included from %s\n' % filename) 166 process(inclfp, outfp, env) 167 else: 168 sys.stderr.write('Warning - could not find file %s\n' % 169 filename) 170 171if __name__ == '__main__': 172 main() 173