~ubuntu-branches/ubuntu/maverick/python3.1/maverick

« back to all changes in this revision

Viewing changes to Tools/scripts/h2py.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2009-03-23 00:01:27 UTC
  • Revision ID: james.westby@ubuntu.com-20090323000127-5fstfxju4ufrhthq
Tags: upstream-3.1~a1+20090322
ImportĀ upstreamĀ versionĀ 3.1~a1+20090322

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#! /usr/bin/env python
 
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
 
 
24
import sys, re, getopt, os
 
25
 
 
26
p_define = re.compile('^[\t ]*#[\t ]*define[\t ]+([a-zA-Z0-9_]+)[\t ]+')
 
27
 
 
28
p_macro = re.compile(
 
29
  '^[\t ]*#[\t ]*define[\t ]+'
 
30
  '([a-zA-Z0-9_]+)\(([_a-zA-Z][_a-zA-Z0-9]*)\)[\t ]+')
 
31
 
 
32
p_include = re.compile('^[\t ]*#[\t ]*include[\t ]+<([a-zA-Z0-9_/\.]+)')
 
33
 
 
34
p_comment = re.compile(r'/\*([^*]+|\*+[^/])*(\*+/)?')
 
35
p_cpp_comment = re.compile('//.*')
 
36
 
 
37
ignores = [p_comment, p_cpp_comment]
 
38
 
 
39
p_char = re.compile(r"'(\\.[^\\]*|[^\\])'")
 
40
 
 
41
p_hex = re.compile(r"0x([0-9a-fA-F]+)L?")
 
42
 
 
43
filedict = {}
 
44
importable = {}
 
45
 
 
46
try:
 
47
    searchdirs=os.environ['include'].split(';')
 
48
except KeyError:
 
49
    try:
 
50
        searchdirs=os.environ['INCLUDE'].split(';')
 
51
    except KeyError:
 
52
        try:
 
53
            if sys.platform.startswith("atheos"):
 
54
                searchdirs=os.environ['C_INCLUDE_PATH'].split(':')
 
55
            else:
 
56
                raise KeyError
 
57
        except KeyError:
 
58
            searchdirs=['/usr/include']
 
59
 
 
60
def main():
 
61
    global filedict
 
62
    opts, args = getopt.getopt(sys.argv[1:], 'i:')
 
63
    for o, a in opts:
 
64
        if o == '-i':
 
65
            ignores.append(re.compile(a))
 
66
    if not args:
 
67
        args = ['-']
 
68
    for filename in args:
 
69
        if filename == '-':
 
70
            sys.stdout.write('# Generated by h2py from stdin\n')
 
71
            process(sys.stdin, sys.stdout)
 
72
        else:
 
73
            fp = open(filename, 'r')
 
74
            outfile = os.path.basename(filename)
 
75
            i = outfile.rfind('.')
 
76
            if i > 0: outfile = outfile[:i]
 
77
            modname = outfile.upper()
 
78
            outfile = modname + '.py'
 
79
            outfp = open(outfile, 'w')
 
80
            outfp.write('# Generated by h2py from %s\n' % filename)
 
81
            filedict = {}
 
82
            for dir in searchdirs:
 
83
                if filename[:len(dir)] == dir:
 
84
                    filedict[filename[len(dir)+1:]] = None  # no '/' trailing
 
85
                    importable[filename[len(dir)+1:]] = modname
 
86
                    break
 
87
            process(fp, outfp)
 
88
            outfp.close()
 
89
            fp.close()
 
90
 
 
91
def pytify(body):
 
92
    # replace ignored patterns by spaces
 
93
    for p in ignores:
 
94
        body = p.sub(' ', body)
 
95
    # replace char literals by ord(...)
 
96
    body = p_char.sub('ord(\\0)', body)
 
97
    # Compute negative hexadecimal constants
 
98
    start = 0
 
99
    UMAX = 2*(sys.maxsize+1)
 
100
    while 1:
 
101
        m = p_hex.search(body, start)
 
102
        if not m: break
 
103
        s,e = m.span()
 
104
        val = int(body[slice(*m.span(1))], 16)
 
105
        if val > sys.maxsize:
 
106
            val -= UMAX
 
107
            body = body[:s] + "(" + str(val) + ")" + body[e:]
 
108
        start = s + 1
 
109
    return body
 
110
 
 
111
def process(fp, outfp, env = {}):
 
112
    lineno = 0
 
113
    while 1:
 
114
        line = fp.readline()
 
115
        if not line: break
 
116
        lineno = lineno + 1
 
117
        match = p_define.match(line)
 
118
        if match:
 
119
            # gobble up continuation lines
 
120
            while line[-2:] == '\\\n':
 
121
                nextline = fp.readline()
 
122
                if not nextline: break
 
123
                lineno = lineno + 1
 
124
                line = line + nextline
 
125
            name = match.group(1)
 
126
            body = line[match.end():]
 
127
            body = pytify(body)
 
128
            ok = 0
 
129
            stmt = '%s = %s\n' % (name, body.strip())
 
130
            try:
 
131
                exec(stmt, env)
 
132
            except:
 
133
                sys.stderr.write('Skipping: %s' % stmt)
 
134
            else:
 
135
                outfp.write(stmt)
 
136
        match = p_macro.match(line)
 
137
        if match:
 
138
            macro, arg = match.group(1, 2)
 
139
            body = line[match.end():]
 
140
            body = pytify(body)
 
141
            stmt = 'def %s(%s): return %s\n' % (macro, arg, body)
 
142
            try:
 
143
                exec(stmt, env)
 
144
            except:
 
145
                sys.stderr.write('Skipping: %s' % stmt)
 
146
            else:
 
147
                outfp.write(stmt)
 
148
        match = p_include.match(line)
 
149
        if match:
 
150
            regs = match.regs
 
151
            a, b = regs[1]
 
152
            filename = line[a:b]
 
153
            if filename in importable:
 
154
                outfp.write('from %s import *\n' % importable[filename])
 
155
            elif filename not in filedict:
 
156
                filedict[filename] = None
 
157
                inclfp = None
 
158
                for dir in searchdirs:
 
159
                    try:
 
160
                        inclfp = open(dir + '/' + filename)
 
161
                        break
 
162
                    except IOError:
 
163
                        pass
 
164
                if inclfp:
 
165
                    outfp.write(
 
166
                            '\n# Included from %s\n' % filename)
 
167
                    process(inclfp, outfp, env)
 
168
                else:
 
169
                    sys.stderr.write('Warning - could not find file %s\n' %
 
170
                                     filename)
 
171
 
 
172
if __name__ == '__main__':
 
173
    main()