-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpxdgen.py
299 lines (229 loc) · 9.13 KB
/
pxdgen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
"""
Auto-generates PXD files from annotated C++ headers.
"""
import re
import os
from pygments.token import Token
from pygments.lexers import get_lexer_for_filename
class ParserError(Exception):
"""
Represents a fatal parsing error in PXDGenerator.
"""
def __init__(self, filename, lineno, message):
super().__init__("{}:{} {}".format(filename, lineno, message))
class PXDGenerator:
"""
Represents, and performs, a single conversion of a C++ header file to a
PXD file.
@param infilename:
input (C++ header) file name. is opened and read.
@param outfilename:
output (pxd) file name. is opened and written.
"""
def __init__(self, infilename, outfilename):
self.infilename = infilename
self.outfilename = outfilename
# current parsing state (not valid until self.parse() is called)
self.stack, self.lineno, self.annotations = None, None, None
def parser_error(self, message, lineno=None):
"""
Returns a ParserError object for this generator, at the current line.
"""
if lineno is None:
lineno = self.lineno
return ParserError(self.infilename, lineno, message)
def tokenize(self):
"""
Tokenizes the input file.
Yields (tokentype, val) pairs, where val is a string.
The concatenation of all val strings is equal to the input file's
content.
"""
# contains all namespaces and other '{' tokens
self.stack = []
# current line number
self.lineno = 1
# we're using the pygments lexer (mainly because that was the first
# google hit for 'python c++ lexer', and it's fairly awesome to use)
lexer = get_lexer_for_filename('.cpp')
with open(self.infilename) as infile:
code = infile.read()
for token, val in lexer.get_tokens(code):
# ignore whitespaces
yield token, val
self.lineno += val.count('\n')
def handle_singleline_comment(self, val):
"""
Breaks down a '//'-style single-line comment, and passes the result
to handle_comment()
@param val:
the comment text, as string, including the '//'
"""
try:
val = re.match('^// (.*)$', val).group(1)
except AttributeError as ex:
raise self.parser_error("invalid single-line comment") from ex
self.handle_comment(val)
def handle_multiline_comment(self, val):
"""
Breaks down a '/* */'-style multi-line comment, and passes the result
to handle_comment()
@param val:
the comment text, as string, including the '/*' and '*/'
"""
try:
val = re.match('^/\\*(.*)\\*/$', val, re.DOTALL).group(1)
except AttributeError as ex:
raise self.parser_error("invalid multi-line comment") from ex
# for a comment '/* foo\n * bar\n */', val is now 'foo\n * bar\n '
# however, we'd prefer ' * foo\n * bar'
val = ' * ' + val.rstrip()
# actually, we'd prefer [' * foo', ' * bar'].
lines = val.split('\n')
comment_lines = []
for idx, line in enumerate(lines):
try:
line = re.match('^ \\*( (.*))?$', line).group(2) or ""
except AttributeError as ex:
raise self.parser_error("invalid multi-line comment line",
idx + self.lineno) from ex
# if comment is still empty, don't append anything
if comment_lines or line.strip() != "":
comment_lines.append(line)
self.handle_comment('\n'.join(comment_lines).rstrip())
def handle_comment(self, val):
"""
Handles any comment, with its format characters removed,
extracting the pxd annotation
"""
annotations = re.findall('pxd:\\s(.*?)(:pxd|$)', val, re.DOTALL)
annotations = [annotation[0] for annotation in annotations]
if not annotations:
raise self.parser_error("comment contains no valid pxd annotation")
for annotation in annotations:
# remove empty lines at end
annotation = annotation.rstrip()
annotation_lines = annotation.split('\n')
for idx, line in enumerate(annotation_lines):
if line.strip() != "":
# we've found the first non-empty annotation line
self.add_annotation(annotation_lines[idx:])
break
else:
raise self.parser_error("pxd annotation is empty:\n" + val)
def add_annotation(self, annotation_lines):
"""
Adds a (current namespace, pxd annotation) tuple to self.annotations.
"""
if "{" in self.stack:
raise self.parser_error("PXD annotation is brace-enclosed")
elif not self.stack:
namespace = None
else:
namespace = "::".join(self.stack)
self.annotations.append((namespace, annotation_lines))
def handle_token(self, token, val):
"""
Handles one token while the parser is in its regular state.
Returns the new state integer.
"""
# accept any token here
if token == Token.Keyword and val == 'namespace':
# advance to next state on 'namespace'
return 1
elif (token, val) == (Token.Punctuation, '{'):
self.stack.append('{')
elif (token, val) == (Token.Punctuation, '}'):
try:
self.stack.pop()
except IndexError as ex:
raise self.parser_error("unmatched '}'") from ex
elif token == Token.Comment.Single and 'pxd:' in val:
self.handle_singleline_comment(val)
elif token == Token.Comment.Multiline and 'pxd:' in val:
self.handle_multiline_comment(val)
else:
# we don't care about all those other tokens
pass
return 0
def parse(self):
"""
Parses the input file.
Internally calls self.tokenize().
Adds all found PXD annotations to self.annotations,
together with info about the namespace in which they were encountered.
"""
self.annotations = []
state = 0
for token, val in self.tokenize():
# ignore whitespaces
if token == Token.Text and not val.strip():
continue
if state == 0:
state = self.handle_token(token, val)
elif state == 1:
# we're inside a namespace definition; expect Token.Name
if token != Token.Name:
raise self.parser_error(
"expected identifier after 'namespace'")
state = 2
self.stack.append(val)
elif state == 2:
# expect {
if (token, val) != (Token.Punctuation, '{'):
raise self.parser_error("expected '{' after 'namespace " +
self.stack[-1] + "'")
state = 0
if self.stack:
raise self.parser_error("expected '}', but found EOF")
def get_pxd_lines(self):
"""
calls self.parse() and processes the pxd annotations to pxd code lines.
"""
yield "# this PXD definition file was auto-generated from {}".format(
self.infilename)
self.parse()
# namespace of the previous pxd annotation
previous_namespace = None
for namespace, annotation_lines in self.annotations:
yield ""
if namespace != previous_namespace:
yield ""
if namespace:
prefix = " "
if namespace != previous_namespace:
yield 'cdef extern from "{}" namespace "{}":'.format(
os.path.relpath(self.infilename,
os.path.dirname(self.outfilename)),
namespace)
else:
prefix = ""
for annotation in annotation_lines:
yield prefix + annotation
previous_namespace = namespace
def generate(self):
"""
reads the input file and writes the output file.
on parsing failure, raises ParserError
"""
try:
with open(self.outfilename, 'w') as outfile:
for line in self.get_pxd_lines():
outfile.write(line)
outfile.write('\n')
except ParserError:
os.remove(self.outfilename)
raise
def main():
""" main function """
import argparse
cli = argparse.ArgumentParser()
cli.add_argument('input', help="input header file")
cli.add_argument('--output', '-o', help="output filename", default=None)
args = cli.parse_args()
infilename, outfilename = args.input, args.output
if outfilename is None:
outfilename = os.path.splitext(infilename)[0] + '.pxd'
PXDGenerator(infilename, outfilename).generate()
if __name__ == '__main__':
main()