Updated for hfsplus module, new gusi libs.
[python/dscho.git] / Tools / scripts / h2py.py
blob055e381226aa66b1255c8d7a52d5a569ce2d30f1
1 #! /usr/bin/env python
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.
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".
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)'".
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?
24 import sys, re, getopt, os
26 p_define = re.compile('^[\t ]*#[\t ]*define[\t ]+([a-zA-Z0-9_]+)[\t ]+')
28 p_macro = re.compile(
29 '^[\t ]*#[\t ]*define[\t ]+'
30 '([a-zA-Z0-9_]+)\(([_a-zA-Z][_a-zA-Z0-9]*)\)[\t ]+')
32 p_include = re.compile('^[\t ]*#[\t ]*include[\t ]+<([a-zA-Z0-9_/\.]+)')
34 p_comment = re.compile(r'/\*([^*]+|\*+[^/])*(\*+/)?')
35 p_cpp_comment = re.compile('//.*')
37 ignores = [p_comment, p_cpp_comment]
39 p_char = re.compile(r"'(\\.[^\\]*|[^\\])'")
41 filedict = {}
42 importable = {}
44 try:
45 searchdirs=os.environ['include'].split(';')
46 except KeyError:
47 try:
48 searchdirs=os.environ['INCLUDE'].split(';')
49 except KeyError:
50 try:
51 if sys.platform.find("beos") == 0:
52 searchdirs=os.environ['BEINCLUDES'].split(';')
53 else:
54 raise KeyError
55 except KeyError:
56 searchdirs=['/usr/include']
58 def main():
59 global filedict
60 opts, args = getopt.getopt(sys.argv[1:], 'i:')
61 for o, a in opts:
62 if o == '-i':
63 ignores.append(re.compile(a))
64 if not args:
65 args = ['-']
66 for filename in args:
67 if filename == '-':
68 sys.stdout.write('# Generated by h2py from stdin\n')
69 process(sys.stdin, sys.stdout)
70 else:
71 fp = open(filename, 'r')
72 outfile = os.path.basename(filename)
73 i = outfile.rfind('.')
74 if i > 0: outfile = outfile[:i]
75 modname = outfile.upper()
76 outfile = modname + '.py'
77 outfp = open(outfile, 'w')
78 outfp.write('# Generated by h2py from %s\n' % filename)
79 filedict = {}
80 for dir in searchdirs:
81 if filename[:len(dir)] == dir:
82 filedict[filename[len(dir)+1:]] = None # no '/' trailing
83 importable[filename[len(dir)+1:]] = modname
84 break
85 process(fp, outfp)
86 outfp.close()
87 fp.close()
89 def process(fp, outfp, env = {}):
90 lineno = 0
91 while 1:
92 line = fp.readline()
93 if not line: break
94 lineno = lineno + 1
95 match = p_define.match(line)
96 if match:
97 # gobble up continuation lines
98 while line[-2:] == '\\\n':
99 nextline = fp.readline()
100 if not nextline: break
101 lineno = lineno + 1
102 line = line + nextline
103 name = match.group(1)
104 body = line[match.end():]
105 # replace ignored patterns by spaces
106 for p in ignores:
107 body = p.sub(' ', body)
108 # replace char literals by ord(...)
109 body = p_char.sub('ord(\\0)', body)
110 stmt = '%s = %s\n' % (name, body.strip())
111 ok = 0
112 try:
113 exec stmt in env
114 except:
115 sys.stderr.write('Skipping: %s' % stmt)
116 else:
117 outfp.write(stmt)
118 match = p_macro.match(line)
119 if match:
120 macro, arg = match.group(1, 2)
121 body = line[match.end():]
122 for p in ignores:
123 body = p.sub(' ', body)
124 body = p_char.sub('ord(\\0)', body)
125 stmt = 'def %s(%s): return %s\n' % (macro, arg, body)
126 try:
127 exec stmt in env
128 except:
129 sys.stderr.write('Skipping: %s' % stmt)
130 else:
131 outfp.write(stmt)
132 match = p_include.match(line)
133 if match:
134 regs = match.regs
135 a, b = regs[1]
136 filename = line[a:b]
137 if importable.has_key(filename):
138 outfp.write('from %s import *\n' % importable[filename])
139 elif not filedict.has_key(filename):
140 filedict[filename] = None
141 inclfp = None
142 for dir in searchdirs:
143 try:
144 inclfp = open(dir + '/' + filename)
145 break
146 except IOError:
147 pass
148 if inclfp:
149 outfp.write(
150 '\n# Included from %s\n' % filename)
151 process(inclfp, outfp, env)
152 else:
153 sys.stderr.write('Warning - could not find file %s\n' %
154 filename)
156 main()