-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathcpp2python.py
More file actions
executable file
·423 lines (320 loc) · 11.1 KB
/
cpp2python.py
File metadata and controls
executable file
·423 lines (320 loc) · 11.1 KB
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
#!/usr/bin/env python3
help = """The script helps to convert C/C++ sources to C/C++ -like Python sources.
It does some simple edit operations like removing semicolons and type declarations.
After it you must edit code manually, but you'll probably spend less time doing it.
Example:
if (a && b) --> if a and b:
{ --> object.method()
object->method(); -->
} -->
The utility **will** make mistakes and **will not** generate ready for use code,
therefore it won't be useful for you unless you know both C/C++ and Python.
For better result, it is recomented to format your code to ANSI style
before doing conversion.
astyle --style=ansi your.cpp source.cpp files.cpp
Usage:
cpp2python.py DIR Find C/C++ files in the directory
by suffix and process.
cpp2python.py FILE Process the file.
cpp2python.py -v|--version|-h|--help Display the help message.
After the processing new file is created.
File name is {old file name with suffix}.py. i.e. main.cpp.py
Author: Andrei Kopats <hlamer@tut.by>
License: GPL
"""
import sys
import os.path
import re
def is_source(filename):
suffixes = ('.cpp', '.c', '.cxx', '.c++', '.cc', '.h', '.hpp', '.hxx', '.h++')
for s in suffixes:
if filename.endswith(s):
return True
return False
def process_line(line):
#DO WHILE
# regex = r"\s(do)\s*\{((\w|\W)*)\}\s*(while)?\(([a-zA-Z0-9\!\=\& ]+)\);"
# subst = "\\2\\4(\\5):\\n\\2"
# line = re.sub(regex, subst, line, 0, re.VERBOSE | re.MULTILINE)
""" remove pointer
double *d
V
d
"""
regex = r"(double|int|char|float)\s+\*\s?(\w+)\b"
subst = "\\2"
# You can manually specify the number of replacements by changing the 4th argument
line = re.sub(regex, subst, line)
""" remove semicolons
codecode(param, param);
V
codecode(param, param)
"""
line = re.sub(';([\r\n]?)$', '\\1', line) # remove semicolon from the end of line
""" remove strings containing opening bracket
if (blabla)
{
codecode
V
if (blabla)
codecode
"""
line = re.sub('\s*{\n$', '', line)
""" remove closing brackets. Empty line preserved
if (blabla)
{
codecode
V
if (blabla)
codecode
"""
line = re.sub('\s*}$', '', line)
""" replace inline comment sign
// here is comment
V
# here is comment
"""
line = re.sub('//', '#', line)
""" replace /* comment sign
/* here is comment
V
''' here is comment
"""
line = re.sub('/\*', "'''", line)
""" replace */ comment sign
here is comment */
V
here is comment '''
"""
line = re.sub('\*/', "'''", line)
""" replace '||' with 'or'
boolvar || anotherboolvar
V
boolvar or anotherboolvar
"""
line = re.sub('\|\|', 'or', line)
""" replace '&&' with 'and'
boolvar && anotherboolvar
V
boolvar and anotherboolvar
"""
line = re.sub('&&', 'and', line)
""" replace '!' with 'not '
if !boolvar
V
if not boolvar
"""
line = re.sub('!([^=\n])', 'not \\1', line)
""" replace '->' with '.'
object->method()
V
object.method()
"""
line = re.sub('->', '.', line)
""" replace 'false' with 'False'
b = false
V
b = False
"""
line = re.sub('false', 'False', line)
""" replace 'true' with 'True'
b = true
V
b = True
"""
line = re.sub('true', 'True', line)
""" remove "const" word from the middle of string
const int result = a.exec();
V
int result = a.exec();
"""
line = re.sub('const ', ' ', line)
""" remove "const" word from the end of string
const int result = a.exec();
V
int result = a.exec();
"""
line = re.sub(' const$', '', line)
""" remove brackets around if statement and add colon
if (i = 4)
V
if i = 4:
"""
line = re.sub('if\s*\((.*)\)$', 'if \\1:', line)
""" remove brackets around if statement and add colon
if (i = 4)
V
if i = 4:
"""
line = re.sub('if\s*\((.*)\)$', 'if \\1:', line)
#return line
""" remove type from method definition and add a colon and "def"
-bool pMonkeyStudio::isSameFile( const QString& left, const QString& right )
+pMonkeyStudio::isSameFile( const QString& left, const QString& right ):
"""
line = re.sub('^[\w:&<>\*]+\s+([\w:]+)\(([^\)]*\))$', 'def \\1(self, \\2:', line)
""" after previous replacement fix "(self, )" to "(self)"
-def internal_projectCustomActionTriggered(self, ):
+def internal_projectCustomActionTriggered(self):
"""
line = re.sub('\(\s*self,\s*\)', '(self)', line)
""" remove type name from function parameters (second and farther)
-def internal_currentProjectChanged(self, XUPProjectItem* currentProject, XUPProjectItem* previousProject ):
+def internal_currentProjectChanged(self, currentProject, previousProject ):
"""
line = re.sub(',\s*[\w\d:&\*<>]+\s+([\w\d:&\*]+)', ', \\1', line)
""" remove type name from variable declaration and initialisation
-pAbstractChild* document = currentDocument()
+document = currentDocument()
"""
line = re.sub('[\w\d:&\*]+\s+([\w\d]+)\s*= ', '\\1 = ', line)
""" remove class name from method definition
-pMonkeyStudio::isSameFile( const QString& left, const QString& right ):
+pMonkeyStudio::isSameFile( const QString& left, const QString& right ):
"""
line = re.sub('^def [\w\d]+::([\w\d]+\([^\)]*\):)$', 'def \\1', line)
""" replace '::' with '.'
YourNameSpace::YourFunction(bla, bla)
V
YourNameSpace.YourFunction(bla, bla)
"""
line = re.sub('::', '.', line)
""" replace 'else if' with 'elif'
else if (blabla)
V
elif (blabla)
"""
line = re.sub('else\s+if', 'elif', line)
""" replace 'else' with 'else:'
if blabala:
pass
else
pass
V
if blabala:
pass
else:
pass
"""
line = re.sub('else\s*$', 'else:\n', line)
""" Remove "new" keyword
-i = new Class
+i = Class
"""
line = re.sub(' new ', ' ', line)
""" Replace "this" with "self"
-p = SomeClass(this)
+p = SomeClass(self)
"""
line = re.sub('([^\w])this([^\w])', '\\1self\\2', line)
""" Replace Qt foreach macro with Python for
-foreach ( QMdiSubWindow* window, a.subWindowList() )
+foreach ( QMdiSubWindow* window, a.subWindowList() )
"""
line = re.sub('foreach\s*\(\s*[\w\d:&\*]+\s+([\w\d]+)\s*,\s*([\w\d\.\(\)]+)\s*\)', 'for \\1 in \\2:', line)
""" Replace Qt signal emit statement
-emit signalName(param, param)
+signalName.emit(param, param)
"""
line = re.sub('emit ([\w\d]+)', '\\1.emit', line)
""" Replace Qt connect call
-connect( combo, SIGNAL( activated( int ) ), self, SLOT( comboBox_activated( int ) ) )
+combo.activated.connect(self.comboBox_activated)
"""
line = re.sub('connect\s*\(\s*([^,]+)\s*,\s*' + \
'SIGNAL\s*\(\s*([\w\d]+)[^\)]+\)\s*\)\s*,'+ \
'\s*([^,]+)\s*,\s*' + \
'S[A-Z]+\s*\(\s*([\w\d]+)[^\)]+\)\s*\)\s*\)',
'\\1.\\2.connect(\\3.\\4)', line)
""" alter for statement
for(j = 1; j < c - 1; j+=1)
v
for j in range(1,c-1,1):
"""
regex = r"for\s?\(\s?(\s?(\w+)\b\s?=\s?(\d+|\w+)\b\s?)?;\s?((\w+)\s?(>|>=|<|<=|==|!=)?\s?((\w+|\d+)?\s?(\-|\+|\*|\/)?\s?(\w+|\d+)?))?\s?;\s?(\w+\s?(\+\+|\-\-|\+|\-)(\d+)?(\w+)?)?\s?\)"
subst = "for \\2 in range(\\3, \\7):"
line = re.sub(regex, subst, line)
""" remove type
int|float|double|char i;
V
i
"""
line = re.sub('(int|double|float|char) ', '', line) #
""" remove ++
i++
V
i+=1
"""
line = re.sub('\+\+', '+=1', line) #
""" remove --
i--
V
i-=1
"""
line = re.sub('--', '-=1', line) #
line = re.sub(';', '', line) #
# ALTER % IN PRINT TO STR() FUNCTION
line = re.sub('printf', 'print', line)
regex = r"print\((\"[\!\+\-\*\\a-zA-Z0-9_ ,\[\]\.\%\:]+\s?\")\,?\s?([\+\-\*\\a-zA-Z0-9_ ,\[\]\.\%\(\)]+)*\)"
subst = "print(\\1, %(\\2))"
# You can manually specify the number of replacements by changing the 4th argument
line = re.sub(regex, subst, line, 0, re.VERBOSE)
line = re.sub('getch\(\)', '', line)
#remove all param a[], a[][] -> a
for x in range(1,10, 1):
regex = r"def\s([0-9\[\]]+)*([a-zA-Z_ \(\)\,]+)([0-9\[\]]+)*"
subst = "def \\2"
line = re.sub(regex, subst, line, 0, re.MULTILINE)
#SCANF
regex = r"scanf\(\"%\w+\"\,\s?\&?\s?([a-zA-Z\[\]_]+)\)"
subst = "\\1 = input()"
line = re.sub(regex, subst, line, 0, re.VERBOSE)
#CALLOC
regex = r"(\w+)\s*\=\s*\((\W*|\w*)*calloc\(([a-zA-Z0-9\-\+\*\ (\)\[\]]*)\,\s(\w)*\(\w*\)\)"
subst = "\\1 = []"
line = re.sub(regex, subst, line, 0, re.VERBOSE)
#FILL ARRAY
regex = r"""
([a-zA-Z0-9_]+)\s*\[([a-zA-Z0-9_]+)\s*((\+=)|(\-=)|(\+\+))\s*([0-9]*)\]\s*\=*\s*
"""
subst = "\\2\\3\\7\n\\1[\\2] = "
line = re.sub(regex, subst, line, 0, re.VERBOSE | re.MULTILINE)
regex = r",\s*%\(\)"
subst = ""
line = re.sub(regex, subst, line, 0, re.VERBOSE | re.MULTILINE)
#NEEDS range(0,(term)) -> range(0, (term)-1)
return line
def process_file(in_filename, out_filename):
"""
generator - outputs processed file
"""
with open(in_filename, 'r') as file:
lines = file.readlines() # probably would die on sources more than 100 000 lines :D
with open(out_filename, 'w+') as file:
for line in lines:
file.write(process_line(line))
def main():
if '--help' in sys.argv or \
'-h' in sys.argv or \
'--version' in sys.argv or \
'-v' in sys.argv:
print(help)
sys.exit(0)
if len (sys.argv) != 2:
print('Invalid parameters count. Must be 1', file=sys.stderr)
print(help)
sys.exit(-1)
if os.path.isdir(sys.argv[1]):
for root, dirs, files in os.walk(sys.argv[1]):
for file in files:
in_filename = root + '/' + file
if is_source(in_filename):
out_filename = in_filename + '.py' # not ideal
process_file(in_filename, out_filename)
elif os.path.isfile(sys.argv[1]):
process_file(sys.argv[1], sys.argv[1] + '.py')
else:
print('Not a file or directory', sys.argv[1], file=sys.stderr)
sys.exit(-1)
if __name__ == '__main__':
main()