/
generate_pygimli_code.py
677 lines (560 loc) · 23.7 KB
/
generate_pygimli_code.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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
import sys
from environment_for_pygimli_build import settings
import hand_made_wrappers
from optparse import OptionParser
optionParser = OptionParser("usage: %prog [options]")
optionParser.add_option("", "--extra-includes", dest="extraIncludes")
optionParser.add_option("", "--extra-path", dest="extraPath")
optionParser.add_option("", "--caster", dest="caster")
optionParser.add_option("", "--clang", dest="clang", default="")
(options, args) = optionParser.parse_args()
print('##############')
print(options)
print(args)
print('##############')
if options.caster:
settings.caster_path = options.caster
if options.extraPath:
print("insert extra path: ", options.extraPath)
sys.path.insert(0, options.extraPath)
from pygccxml import parser
import logging
from pygccxml import utils
logger = utils.loggers.cxx_parser
#logger.setLevel(logging.DEBUG)
from pygccxml import declarations
from pygccxml.declarations import access_type_matcher_t
from pyplusplus import code_creators, module_builder, messages, decl_wrappers
from pyplusplus.module_builder import call_policies
from pyplusplus.decl_wrappers.doc_extractor import doc_extractor_i
import hashlib
MAIN_NAMESPACE = 'GIMLI'
def samefile(sourcefile, destfile):
"""
"""
if not os.path.exists(destfile):
return False
if not os.path.exists(sourcefile):
return False
inhash = hashlib.md5()
inhash.update(open(sourcefile).read().encode('utf-8'))
outhash = hashlib.md5()
outhash.update(open(destfile).read().encode('utf-8'))
if inhash.digest() != outhash.digest():
return False
# probably don't need these as hash should handle it fine..
if os.stat(sourcefile).st_mtime > os.stat(destfile).st_mtime:
return False
if os.stat(sourcefile).st_size != os.stat(destfile).st_size:
return False
return True
class decl_starts_with (object):
def __init__(self, prefix):
self.prefix = prefix
def __call__(self, decl):
return self.prefix in decl.name
def exclude(method, return_type='', name='', symbol=''):
for funct in return_type:
if len(funct):
fun = method(return_type=funct, allow_empty=True)
for f in fun:
# print("exclude return type", f)
f.exclude()
for funct in name:
if len(funct):
fun = method(name=funct, allow_empty=True)
for f in fun:
# print("exclude name", f)
f.exclude()
for funct in symbol:
if len(funct):
fun = method(symbol=funct, allow_empty=True)
for f in fun:
# print("exclude symbol", f)
f.exclude()
def setMemberFunctionCallPolicieByReturn(mb, MemberRetRef, callPolicie):
for ref in MemberRetRef:
memFuns = mb.global_ns.member_functions(
return_type=ref,
allow_empty=True)
# print(ref, len(memFuns))
for memFun in memFuns:
if memFun.call_policies:
continue
else:
memFun.call_policies = \
call_policies.return_value_policy(callPolicie)
class docExtractor(doc_extractor_i):
def __init__(self):
doc_extractor_i.__init__(self)
# def __call__(self, decl):
# print "__call__(self, decl):", decl
# print decl.location.file_name
# print decl.location.line
# return ""Doku here""
def escape_doc(self, doc):
return '"' + doc + '"'
def extract(self, decl):
# print(decl.location.file_name)
# print(decl.location.line)
# print("extract(self, decl):", decl)
return "Doku coming soon"
def generate(defined_symbols, extraIncludes):
messages.disable(
messages.W1005 # using a non public variable type for arguments or returns
, messages.W1006 # `Py++` need your
# help to expose function that takes > as argument/returns C++ arrays.
# Take a look on "Function Transformation" > functionality and define
# the transformation.
, messages.W1007 # more than 10 args -> BOOST_PYTHON_MAX_ARITY is set
, messages.W1009 # execution error W1009: The function takes as argument (name=pFunIdx, pos=1) >
# non-const reference to Python immutable type - function could not be called > from Python
, messages.W1014 # "operator*" is not supported. See
, messages.W1016 # `Py++` does not exports non-const casting operators
# Warnings 1020 - 1031 are all about why Py++ generates wrapper for class X
, messages.W1023 # Py++` will generate class wrapper - there are few functions that should be
# redefined in class wrapper
, messages.W1025 # `Py++` will generate class wrapper - class contains "c_" - T* > member variable
, messages.W1026 # `Py++` will generate class wrapper - class contains "arr_" - T& > member variable
, messages.W1027 # `Py++` will generate class wrapper - class contains "mat_" - > array member variable
, messages.W1035 # error. `Py++` can not expose static pointer member variables.
, messages.W1036 # error. `Py++` can not expose pointer to Python immutable > member variables. This
# could be changed in future.
, messages.W1040 # error. The declaration is unexposed, but there are other > declarations, which
# refer to it. This could cause "no to_python converter > found" run
# time error
# This is serious and lead to RuntimeError: `Py++` is going to write different content to the same file
, messages.W1047 # There are two or more classes that use same > alias("MatElement"). Duplicated aliases causes
# few problems, but the main one > is that some of the classes will not
# be exposed to Python.Other classes : >
, messages.W1049 # This method could not be overriden in Python - method returns >
# reference to local variable!
, messages.W1052 # `Py++` will not expose free operator
)
logger.debug("Install SRC: ", os.path.abspath(__file__))
logger.debug("Execute from: ", os.getcwd())
sourcedir = os.path.dirname(os.path.abspath(__file__))
sourceHeader = os.path.abspath(sourcedir + "/" + r"pygimli.h")
gimliInclude = os.path.dirname(
os.path.abspath(sourcedir + "/../src/" + r"gimli.h"))
settings.includesPaths.append(gimliInclude)
xml_cached_fc = parser.create_cached_source_fc(
sourceHeader, settings.module_name + '.cache')
import platform
defines = ['PYGIMLI_CAST', 'HAVE_BOOST_THREAD_HPP']
caster = 'gccxml'
compiler_path = options.clang
if platform.system() == 'Windows':
if platform.architecture()[0] == '64bit':
#compiler_path = 'C:/msys64/mingw64/bin/clang++'
if sys.platform == 'darwin':
pass
else:
defines.append('_WIN64')
defines.append('MS_WIN64')
logger.info('Marking win64 for gccxml')
else:
pass
#compiler_path = 'C:/msys32/mingw32/bin/clang++'
if len(compiler_path) == 0:
compiler_path = None
for define in [settings.gimli_defines, defined_symbols]:
if len(define) > 0:
defines.append(define)
try:
if sys.platform == 'win32':
# os.name == 'nt' (default on my mingw)results in wrong commandline
# for gccxml
os.name = 'mingw'
casterpath = settings.caster_path.replace('\\', '\\\\')
casterpath = settings.caster_path.replace('/', '\\')
if 'gccxml' not in casterpath:
caster = 'castxml'
if '.exe' not in casterpath:
casterpath += '\\' + caster + '.exe'
else:
casterpath = settings.caster_path
if 'gccxml' not in casterpath:
caster = 'castxml'
except Exception as e:
logger.info("caster_path=%s" % casterpath)
logger.info(str(e))
raise Exception("Problems determine castxml binary")
settings.includesPaths.insert(0, os.path.abspath(extraIncludes))
logger.info("caster_path=%s" % casterpath)
logger.info("working_directory=%s" % settings.gimli_path)
logger.info("include_paths=%s" % settings.includesPaths)
logger.info("define_symbols=%s" % defines)
logger.info("compiler_path=%s" % compiler_path)
logger.info("indexing_suite_version=2")
xml_generator_config = parser.xml_generator_configuration_t(
xml_generator=caster,
xml_generator_path=casterpath,
working_directory=settings.gimli_path,
include_paths=settings.includesPaths,
define_symbols=defines,
ignore_gccxml_output=False,
cflags="",
compiler_path=compiler_path)
mb = module_builder.module_builder_t(
[xml_cached_fc],
indexing_suite_version=2,
xml_generator_config=xml_generator_config
)
logger.info("Reading of c++ sources done.")
mb.classes().always_expose_using_scope = True
mb.calldefs().create_with_signature = True
global_ns = mb.global_ns
global_ns.exclude()
main_ns = global_ns.namespace(MAIN_NAMESPACE)
main_ns.include()
# for c in main_ns.free_functions():
# print(c)
# if 'pow' in c.name:
# print(c)
# print(c.name)
# if c.decl_string.startswith('::GIMLI::pow'):
# print(c)
# print(c.name)
# sys.exit()
logger.info("Apply handmade wrappers.")
try:
hand_made_wrappers.apply(mb)
except BaseException as e:
print(e)
logger.info("Apply custom rvalues.")
# START manual r-value converters
rvalue_converters = [
'register_pytuple_to_rvector3_conversion',
'register_pysequence_to_rvector_conversion',
#'register_pysequence_to_cvector_conversion', .. will not work
'register_pysequence_to_ivector_conversion',
'register_pysequence_to_bvector_conversion',
'register_pysequence_to_indexvector_conversion',
'register_pysequence_to_ivector_conversion',
'register_pysequence_to_r3vector_conversion',
'register_pysequence_to_StdVectorRVector3_conversion',
'register_numpy_to_int64_conversion',
'register_numpy_to_uint64_conversion',
'register_numpy_to_double_conversion',
'register_numpy_to_rmatrix_conversion',
'register_numpy_to_int32_conversion',
'register_numpy_to_uint32_conversion',
]
for converter in rvalue_converters:
mb.add_declaration_code('void %s();' % converter)
mb.add_registration_code('%s();' % converter)
# END manual r-value converters
custom_rvalue_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'custom_rvalue.cpp')
logger.info("Starting to exclude stuff that we don't need "
"or that is known to be spurious.")
exclude(main_ns.variables,
name=[
'Triangle6_S1',
'Triangle6_S2',
'Triangle6_S3',
'HexahedronFacesID',
'Hexahedron20FacesID',
'TetrahedronFacesID',
'HexahedronSplit5TetID',
'HexahedronSplit6TetID',
'TriPrismFacesID',
'TriPrimSplit3TetID',
'NodeCoordinates',
'EdgeCoordinates',
'TriCoordinates',
'QuadCoordinates',
'TetCoordinates',
'HexCoordinates',
'PrismCoordinates',
'PyramidCoordinates',
'PyramidFacesID',
'Tet10NodeSplit',
'Tet10NodeSplitZienk',
'Hex20NodeSplit',
'Prism15NodeSplit',
'Pyramid13NodeSplit',
]
)
exclude(main_ns.free_functions,
return_type=[
'float *',
'float &',
"::GIMLI::__VectorExpr< double, " +
"GIMLI::__VectorUnaryExprOp< double, " +
"GIMLI::VectorIterator< double >, GIMLI::ABS_ > >"],
name=[
'strReplaceBlankWithUnderscore',
'toStr',
'toInt',
'toFloat',
'toDouble',
'str',
'getRowSubstrings',
'getNonEmptyRow',
'getSubstrings',
'abs',
'type',
'::GIMLI::print',
'print',
'range',
]
)
exclude(main_ns.free_operators,
name=[''],
return_type=['::std::ostream &', '::std::istream &']
)
exclude(main_ns.classes,
name=['ABS_', 'ACOT', 'ATAN', 'COS', 'COT', 'EXP', 'EXP10',
'ABS_', 'LOG', 'LOG10', 'SIGN', 'SIN', 'SQRT', 'SQR',
'TAN', 'TANH',
'PLUS', 'MINUS', 'MULT', 'DIVID', 'BINASSIGN', 'cerrPtr',
'ISINF', 'ISINFNAN',
'cerrPtrObject', 'coutPtr', 'coutPtrObject', 'deletePtr',
'edge_',
'distancePair_', 'IPCMessage', 'PythonGILSave',
'XAxis__', 'YAxis__', 'ZAxis__',
'Variable',
'BVectorIter',
'CVectorIter',
'RVectorIter',
'Electrode',
'ElectrodeShape',
'ElectrodeShapeDomain',
'ElectrodeShapeEntity',
'ElectrodeShapeNode',
'ElectrodeShapeNodesWithBypass',
'FunctionDD',
'H2SparseMapMatrix',
]
)
exclude(main_ns.member_functions,
name=['begin',
'end',
'val'],
return_type=['']
)
exclude(main_ns.member_operators,
symbol=[''])
for f in main_ns.declarations:
if isinstance(f, decl_wrappers.calldef_wrapper.free_function_t):
if (str(f.return_type).find('GIMLI::VectorExpr') != -1):
f.exclude()
ex = ['::GIMLI::MatrixElement',
'::GIMLI::__VectorUnaryExprOp',
'::GIMLI::__VectorBinaryExprOp',
'::GIMLI::__ValVectorExprOp',
'::GIMLI::__VectorValExprOp',
'::GIMLI::__VectorExpr',
'::GIMLI::Expr',
'::GIMLI::InversionBase',
'GIMLI::XAxis__',
'::GIMLI::YAxis__',
'GIMLI::ZAxis__',
'GIMLI::ElectrodeShape',
'GIMLI::MatrixElement',
'GIMLI::__VectorUnaryExprOp',
'GIMLI::__VectorBinaryExprOp',
'GIMLI::__ValVectorExprOp',
'GIMLI::__VectorValExprOp',
'GIMLI::__VectorExpr',
'GIMLI::Expr',
'GIMLI::InversionBase',
'std::vector<unsigned long',
'std::vector<bool',
'std::vector<double',
'std::set<std',
# 'std::set<Node*', # we need them
# 'std::set<Cell*', # we need them
# 'std::set<Boundary*', # we need them
'Variable',
'Variable<GIMLI::XAxis__',
'BVectorIter',
'CVectorIter',
'IVectorIter',
'RVectorIter',
'FunctionDD',
'::GIMLI::print',
'print',
'range',
]
for c in main_ns.free_functions():
for e in ex:
if c.decl_string.find(e) > -1:
try:
c.exclude()
logger.debug("Exclude: " + str(c))
except BaseException as _:
logger.debug("Fail to exclude: " + str(c))
for c in main_ns.classes():
for e in ex:
if c.decl_string.find(e) > -1:
try:
c.exclude()
logger.debug("Exclude: " + c.name)
except BaseException as _:
logger.debug("Fail to exclude: " + c.name)
try:
for mem in c.variables():
print(mem)
try:
pass
#mem.exclude()
# logger.info("Exclude: " + str(mem))
except BaseException as _:
logger.debug("Fail to exclude: " + str(mem))
except BaseException as _:
# print(c, "has no member functions")
pass
try:
for mem in c.constructors():
for e in ex:
if mem.decl_string.find(e) > -1:
try:
mem.exclude()
# logger.info("Exclude: " + str(mem))
except BaseException as _:
logger.debug("Fail to exclude: " + str(mem))
for mem in c.member_functions():
for e in ex:
if mem.decl_string.find(e) > -1:
try:
mem.exclude()
# logger.info("Exclude: " + str(mem))
except BaseException as _:
logger.debug("Fail to exclude: " + str(mem))
except BaseException as _:
# print(c, "has no member functions")
pass
# print('#'*100)
# print(c, c.name)
if c.name.startswith('Vector<unsigned long>'):
# print(' ', c.name)
for mem in c.constructors():
# print("mem", mem, mem.decl_string)
if mem.decl_string.find('( ::GIMLI::Index )') > -1:
logger.debug("Exclude: " + str(mem))
mem.exclude()
# print("mem", mem)
try:
mb.calldefs(access_type_matcher_t('protected')).exclude()
mb.calldefs(access_type_matcher_t('private')).exclude()
except BaseException as _:
pass
# setMemberFunctionCallPolicieByReturn(mb, [ '::GIMLI::Node &'
# , '::GIMLI::Cell &'
# , '::GIMLI::Boundary &'
# , '::GIMLI::Shape &'
# , '::GIMLI::Node *'
# , '::GIMLI::Cell *'
# , '::GIMLI::Boundary *'
# , '::GIMLI::Shape *'
# ]
# , call_policies.reference_existing_object)
setMemberFunctionCallPolicieByReturn(
mb,
['::std::string *', 'float *', 'double *',
'int *',
'long *',
'long int *',
'long long int *',
'unsigned int *',
'long unsigned int *',
'unsigned long long int *',
'long long unsigned int *',
'::GIMLI::Index *', '::GIMLI::SIndex *', 'bool *'],
call_policies.return_pointee_value)
setMemberFunctionCallPolicieByReturn(mb, ['::std::string &',
'float &',
'double &',
'int &',
'long &',
'long int &',
'long long int &',
'unsigned int &',
'long unsigned int &',
'long long unsigned int &',
'unsigned long long int &',
'::GIMLI::Index &',
'::GIMLI::SIndex &',
'bool &'
], call_policies.return_by_value)
# setMemberFunctionCallPolicieByReturn(mb,
# ['::GIMLI::VectorIterator<double> &']
# , call_policies.copy_const_reference)
# setMemberFunctionCallPolicieByReturn(mb, [
# , 'double &' ]
# , call_policies.reference_existing_object)
# call_policies.return_value_policy(call_policies.reference_existing_object)
# call_policies.return_value_policy(call_policies.copy_non_const_reference)
# call_policies.return_value_policy(call_policies.copy_const_reference)
# addAutoConversions(mb)
# excludeMemberByReturn(main_ns, ['::DCFEMLib::SparseMatrix<double> &'])
# fun = mb.global_ns.member_functions('begin', allow_empty=True)
# for f in fun:
# f.exclude()
# excludeFreeFunctionsByName(main_ns, ['strReplaceBlankWithUnderscore'
# 'toStr', 'toInt', 'toFloat', 'toDouble',
# 'getRowSubstrings', 'getNonEmptyRow', 'getSubstrings' ])
# excludeFreeFunctionsByReturn(main_ns, [ 'float *', 'float &' ])
# fun = ns.free_operators(return_type=funct, allow_empty=True)
# excludeMemberOperators(main_ns, ['++', '--', '*'])
# exclude all that does not match any predefined callpolicie
excludeRest = True
if excludeRest:
mem_funs = mb.calldefs()
for mem_fun in mem_funs:
if mem_fun.call_policies:
continue
if not mem_fun.call_policies and \
(declarations.is_reference(mem_fun.return_type) or
declarations.is_pointer(mem_fun.return_type)):
# print mem_fun
# mem_fun.exclude()
mem_fun.call_policies = call_policies.return_value_policy(
call_policies.reference_existing_object)
# mem_fun.call_policies = \
# call_policies.return_value_policy(call_policies.return_pointee_value)
# mem_fun.call_policies = \
# call_policies.return_value_policy(call_policies.return_opaque_pointer)
# mem_fun.call_policies = \
# call_policies.return_value_policy(call_policies.copy_non_const_reference)
logger.info("Create api documentation from Doxgen comments.")
# Now it is the time to give a name to our module
from doxygen import doxygen_doc_extractor
extractor = doxygen_doc_extractor()
logger.info("Create code creator.")
mb.build_code_creator(settings.module_name, doc_extractor=extractor)
# It is common requirement in software world-each file should have license
# mb.code_creator.license = '//Boost Software
# License(http://boost.org/more/license_info.html)'
# I don't want absolute includes within code
mb.code_creator.user_defined_directories.append(os.path.abspath('.'))
# And finally we can write code to the disk
def ignore(val):
pass
logger.info("Create bindings code.")
mb.split_module('./generated', on_unused_file_found=ignore)
additional_files = [
os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'custom_rvalue.cpp'),
os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'generators.h'),
os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'tuples.hpp')]
logger.info("Add additional files.")
for sourcefile in additional_files:
p, filename = os.path.split(sourcefile)
destfile = os.path.join('./generated', filename)
if not samefile(sourcefile, destfile):
shutil.copy(sourcefile, './generated')
logger.info("Updated " + filename +
"as it was missing or out of date")
if __name__ == '__main__':
defined_symbols = ''
generate(defined_symbols, options.extraIncludes)