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