forked from vegardjervell/fortwrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fortwrap.py
executable file
·2292 lines (2060 loc) · 94.6 KB
/
fortwrap.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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2010 John McFarland
# This program is licensed under the MIT license. See LICENSE.txt
# Author: John McFarland
# This program will parse a selected set of Fortran source files and
# write C++ code to wrap the Fortran derived types in C++ classes
# Run fortwrap.py -h for usage information
from __future__ import print_function
# These imports were added by futurize. In Python 2, the builtins
# module requires the "future" package. These imports allow python 2
# to use the newer versions of the functions. However, the code will
# still work in Python 2 without these, so we can ignore the import
# error.
try:
from builtins import str
from builtins import range
from builtins import object
# Not automatically added by future:
from builtins import dict # If available, enable efficient iteration in Python 2. Another option would be to use itervalues from six.
except ImportError:
# Get here with a Python 2 that does not have the future package.
# However, fortwrap will still work
pass
import argparse
import re
import glob
from datetime import date
import sys
import os
import traceback
VERSION = '2.4.0'
# SETTINGS ==========================================
# Default Fortran compiler. Can be overridden by command option
compiler = 'gfortran'
ERROR_FILE_NAME = 'FortWrap-error.txt'
code_output_dir = '.'
include_output_dir = '.'
fort_output_dir = '.'
HEADER_STRING = '/* This source file automatically generated on ' + str(date.today()) + ' using \n FortWrap wrapper generator version ' + VERSION + ' */\n'
func_pointer_converter = 'convert_c_funcpointer'
misc_defs_filename = 'InterfaceDefs.h'
matrix_classname = 'FortranMatrix'
string_classname = 'FortranString'
orphan_classname = 'FortFuncs'
orphan_class_comments = ['Wrapper class for Fortran routines that do not operate on a derived type']
constants_classname = 'FortConstants'
fort_wrap_file = 'CppWrappers'
SWIG = True # Whether or not to include preprocessor defs that will
# be used by swig
# Macros to define DLLEXPORT, needed with MSC compiler
DLLEXPORT_MACRO = """#ifdef _MSC_VER
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif"""
# ===================================================
# REGULAR EXPRESSIONS ===============================
fort_type_def = re.compile(r'\s*TYPE(\s+(?P<name0>[a-z]\w*)|.*::\s*(?P<name1>[a-z]\w*))', re.IGNORECASE)
fort_type_extends_def = re.compile(r'EXTENDS\s*\(\s*([a-z]\w*)\s*\)', re.IGNORECASE)
fort_tbp_def = re.compile(r'\s*PROCEDURE\s*(\(\s*(?P<interface>[a-z]\w*)\))?.*::', re.IGNORECASE)
fort_proc_def = re.compile(r'\s*(RECURSIVE)?\s*(SUBROUTINE|FUNCTION)\s+\S+\(', re.IGNORECASE)
fort_end_proc = re.compile(r'\s*END\s*(SUBROUTINE|FUNCTION)', re.IGNORECASE)
fort_end_interface = re.compile(r'\s*END\s*INTERFACE', re.IGNORECASE)
fort_comment = re.compile('\s*!')
fort_contains = re.compile(r'\s*CONTAINS\s*$', re.IGNORECASE)
# Data types
primitive_data_str = '(INTEGER|REAL|DOUBLE PRECISION|LOGICAL|CHARACTER|INT|COMPLEX)(\s*(\*(?P<old_kind_spec>[0-9]+)|\(\s*((KIND|len)\s*=)?\s*(?P<kind_spec>(\w+|\*))\s*\)))?'
primitive_data = re.compile(primitive_data_str,re.IGNORECASE)
fort_data_str = r'\s*(' + primitive_data_str + '|(?P<dt_mode>TYPE|CLASS)\s*\((?P<dt_spec>\S*)\)|PROCEDURE\s*\((?P<proc_spec>\S*)\))'
fort_data = re.compile(fort_data_str,re.IGNORECASE)
fort_data_def = re.compile(fort_data_str + '\s*(?P<attributes>,.*)?::',re.IGNORECASE)
optional_def = re.compile('OPTIONAL', re.IGNORECASE)
byval_def = re.compile('VALUE', re.IGNORECASE)
allocatable_def = re.compile('ALLOCATABLE',re.IGNORECASE)
fort_pointer_def = re.compile('POINTER',re.IGNORECASE)
# CLASS: not yet supported, but print warnings
fort_class_data_def = re.compile(r'\s*CLASS\s*\(\S*\).*::',re.IGNORECASE)
module_def = re.compile(r'\s*MODULE\s+\S',re.IGNORECASE)
end_module_def = re.compile(r'\s*END\s+MODULE',re.IGNORECASE)
# INT below is used to represent the hidden length arguments, passed by value
fort_dox_comments = re.compile(r'\s*!\>')
fort_dox_inline = re.compile(r'\s*\w+.*!\<')
result_name_def = re.compile(r'.*RESULT\s*\(\s*(\w+)\s*\)',re.IGNORECASE)
intent_in_def = re.compile(r'.*INTENT\s?\(\s*IN\s*\)',re.IGNORECASE)
intent_out_def = re.compile(r'.*INTENT\s?\(\s*OUT\s*\)',re.IGNORECASE)
fort_abstract_def = re.compile(r'\s*ABSTRACT\s+INTERFACE',re.IGNORECASE)
integer_param_def = re.compile(r'\s+INTEGER,\s+PARAMETER\s+::',re.IGNORECASE)
# Regular expression to break up arguments. This is needed to handle
# multi-dimensional arrays (e.g. A(m,n)). It uses a negative
# lookahead assertion to exclude commas inside the array definition
arg_splitter = re.compile(',(?![^(]*\))')
dimension_def = re.compile(r'DIMENSION\s*\(\s*([^(]+)\s*\)',re.IGNORECASE)
enum_def = re.compile(r'\s*ENUM,\s*BIND',re.IGNORECASE)
# Constructor and desctructor methods (these regexes are configurable):
ctor_def = re.compile('.*_ctor', re.IGNORECASE)
dtor_def = re.compile('.*_dtor', re.IGNORECASE)
# Regular expression for "initialization" functions (configurable):
init_func_def = None
# ===================================================
# GLOBAL VARIABLES ==================================
objects = dict() # lower case object name -> DerivedType instance
procedures = []
abstract_interfaces = dict()
name_substitutions = dict()
pattern_substitutions = [] # List of (regex,replace) tuples
name_exclusions = set()
name_inclusions = set()
proc_arg_exclusions = set()
nopass_tbps = dict() # (module.lower,procname.lower) -> TypeBoundProcedure, for all TBP's with NOPASS attribute
# 'INT' is for the hidden name length argument
cpp_type_map = {'INTEGER':{'':'int*','1':'signed char*','2':'short*','4':'int*','8':'long long*','C_INT':'int*', 'C_LONG':'long*'},
'REAL':{'':'float*', '4':'float*', '8':'double*', 'C_DOUBLE':'double*', 'C_FLOAT':'float*'},
'LOGICAL':{'':'int*', 'C_BOOL':'int*'},
'CHARACTER':{'':'char*'},
'C_PTR':{'':'void**'},
'COMPLEX':{'':'std::complex<float>*','4':'std::complex<float>*','C_FLOAT_COMPLEX':'std::complex<float>*','8':'std::complex<double>*','C_DOUBLE_COMPLEX':'std::complex<double>*'},
'INT':{'':'fortran_charlen_t'}}
current_module = ''
module_proc_num = 1 # For keeping track of the order that the
# procedures are defined in the Fortran code. Not
# needed now that they are stored in a list, but
# keep in case want to use later to achieve a
# different ordering than is in the source
dox_comments = []
fort_integer_params = dict()
enumerations = []
PRIVATE=1
PUBLIC=0
# Indicate whether or not we will need procedure pointer wrapper code
proc_pointer_used = False
# Whether or not matrices are used
matrix_used = False
stringh_used = False # Whether "string.h" is used (needed for strcpy)
fort_class_used = False
string_class_used = False # Whether string outputs are used, which involves wrapping using a string class (either std::string or the generated wrapper class)
complex_used = False
# Gets changed to string_classname if --no-std-string is set
string_object_type = 'std::string'
not_wrapped = [] # List of procedures that weren't wrapped
# ===================================================
class FWTypeException(Exception):
"""Raised when an unexpected type is enountered in the code generation
phase"""
def __init__(self,type):
self.type = type
def __str__(self):
return self.type
def warning(msg):
sys.stderr.write('Warning: ' + msg + '\n')
def error(msg):
sys.stderr.write('Error: ' + msg + '\n')
class Array(object):
two_d_warning_written = False
multi_d_warning_written = False
def __init__(self,spec):
global matrix_used
# spec is the part inside the parentheses
self.assumed_shape = False
self.size_var = ''
self.d = spec.count(',') + 1
if ':' in spec:
self.assumed_shape = True
if self.d == 1:
self.size_var = spec.strip()
elif self.d == 2 and not opts.no_fmat:
matrix_used = True
self.size_var = tuple([v.strip() for v in spec.split(',')])
if self.d==2 and opts.no_fmat:
if not Array.two_d_warning_written:
warning("Wrapping 2-D arrays as pointers can lead to ambiguity if writing SWIG typemaps for pointers. This can be avoided by not using --no-fmat")
Array.two_d_warning_written = True
if self.d>2:
if not Array.multi_d_warning_written:
warning("Wrapping higher-dimensional arrays as pointers can lead to ambiguity if writing SWIG typemaps for pointers.")
Array.multi_d_warning_written = True
# Properties queried by the wrapper generator:
# vec=vector: 1-d array
self.vec = self.d==1 and not self.assumed_shape
self.matrix = self.d==2 and not self.assumed_shape
self.fort_only = self.assumed_shape
class CharacterLength(object):
"""
val may be either a number, or in the case of assumed length, a
string containing the argument name, which is needed in the
wrapper code
"""
def __init__(self,val):
self.val = val
self.assumed = False
def set_assumed(self, argname):
self.val = argname
self.assumed = True
def as_string(self):
if self.assumed:
return self.val+'_len__'
else:
return str(self.val)
class DataType(object):
def __init__(self,type,array=None,str_len=None,hidden=False):
global stringh_used, complex_used
self.type = type
self.kind = ''
self.array = array
self.str_len = str_len
self.proc_pointer = False
self.proc = False # PROCEDURE without POINTER attribute
self.dt = False # False, 'TYPE', or 'CLASS'
self.hidden = hidden # hidden name length arg
# For array, name of argument used to pass the array length:
self.is_array_size = False # integer defining an array size
self.is_matrix_size = False
if type=='CHARACTER':
stringh_used = True # Really only needed for intent(in)
elif type.upper()=='COMPLEX':
complex_used = True
primitive_data_match = primitive_data.match(type)
if primitive_data_match:
# This line must be outside the next two checks since they
# won't catch the case of just 'real'
self.type = primitive_data_match.group(1).upper()
if primitive_data_match.group('old_kind_spec'):
self.kind = primitive_data_match.group('old_kind_spec')
elif primitive_data_match.group('kind_spec'):
self.kind = primitive_data_match.group('kind_spec')
if type.upper() == 'DOUBLE PRECISION':
self.type = 'REAL'
self.kind = '8'
# Handle use of named parameter as kind:
if self.kind.upper() in fort_integer_params:
self.kind = str(fort_integer_params[self.kind.upper()])
if not self.valid_primitive():
warning(self.type+'('+self.kind+') not supported')
if not primitive_data_match and type!='INT':
# (INT is used to represent the hidden length arguments,
# passed by value)
if 'PROCEDURE' in type.upper():
m = fort_data.match(type)
self.type = m.group('proc_spec')
# Outside of this constructor, the pointer attribute
# is checked, in which case "proc" is reset to False
# and "proc_pointer" is set to True:
self.proc = True
else:
m = fort_data.match(type)
if m.group('dt_mode'):
self.dt = m.group('dt_mode').upper()
self.type = m.group('dt_spec')
if self.type.upper() == 'C_PTR':
# Don't treat like derived type
self.dt = False
else:
raise FWTypeException(type)
# Properties queried by the wrapper generator:
# vec=vector: 1-d array
self.vec = self.array and self.array.vec
self.matrix = self.array and self.array.matrix
# Determine whether type is a valid primitive type. Intended to
# verify KIND specs. Doesn't check string lengths. Kind specs
# should already be stripped from type string and stored in kind
# variable
def valid_primitive(self):
type_map = cpp_type_map.get(self.type)
return type_map and self.kind.upper() in type_map
class Argument(object):
def __init__(self,name,pos,type=None,optional=False,intent='inout',byval=False,allocatable=False,pointer=False,comment=[]):
global string_class_used
self.name = name
self.pos = pos # Zero-indexed
self.type = type
self.comment = comment
self.optional = optional
self.intent = intent
self.byval = byval
self.allocatable = allocatable
self.pointer = pointer # (doesn't include procedure pointers)
self.native = False # Will get defined in
# associate_procedures; identifies derived
# type arguments that will get passed in
# C++ using native classes
self.exclude = False # Whether it is excluded via the ignores file
self.cpp_optional = False # Whether or not it is optional to C++
# Whether or not the argument is inside an abstract procedrue
# definition. This is not set on initialization, but later
# during parsing. (Added this attribute to get "const"
# statements to show up in the func pointer defs, which don't
# use pass_by_val)
self.in_abstract = False
# Whether it represents the "self" argument of a method call
self.is_self_arg = False
if type and type.type=='CHARACTER' and intent!='in':
string_class_used = True
if opts.document_all_params and not self.comment:
# Add an empty comment, which will trigger a \param entry
# to be included in the generated doxygen comments
self.comment = ['']
def set_type(self,type):
self.type = type
def pass_by_val(self):
"""Whether we can pass this argument by val in the C++ interface
Don't count Fortran arguments having the VALUE attribute, since they are already passed by value"""
return not self.byval and not self.optional and not self.type.dt and self.intent=='in' and not self.type.array and not self.type.type=='CHARACTER' and not self.in_abstract
def fort_only(self):
if self.type.hidden:
return True
elif self.type.is_array_size or self.type.is_matrix_size:
return True
if self.type.array and self.type.array.fort_only:
return True
elif self.exclude:
return True
elif self.type.dt:
if self.type.array:
return True
elif self.type.proc_pointer:
if not self.type.type in abstract_interfaces:
return True
elif not self.intent=='in':
return True
elif self.type.proc:
# PROCEDURE (without POINTER attribute) does not seem to be compatible with current wrapping approach (with gfortran)
return True
elif self.type.type=='CHARACTER':
if not self.intent=='inout' and self.type.str_len and not self.type.array:
return False
else:
return True
if self.type.type in cpp_type_map and not self.type.valid_primitive():
return True
if self.byval and (self.optional or self.type.dt or self.type.type=='CHARACTER' or self.type.proc_pointer):
return True
if self.allocatable:
return True
if self.pointer and not self.type.proc_pointer:
return True
return False
def cpp_const(self):
"""Whether or not it can be const in C++"""
# matrix and array types excluded because we don't want
# FortranMatrix<const double>. Exclude pass_by_val for
# aesthetic reasons (to keep const from being applied to
# non-pointer arguments in method definitions)
return self.intent=='in' and not self.byval and not self.pass_by_val() and not self.type.matrix
def cpp_type(self, value=False, native=False):
"""
Convert a Fortran type to a C++ type.
"""
if self.type.dt:
if native:
return self.type.type + '*'
else:
return 'ADDRESS'
elif self.type.valid_primitive():
if self.cpp_const():
prefix = 'const '
else:
prefix = ''
string = prefix + cpp_type_map[self.type.type.upper()][self.type.kind]
if value or self.byval:
return string[:-1] # Strip "*"
else:
return string
elif self.type.proc_pointer and self.type.type in abstract_interfaces:
proc = abstract_interfaces[self.type.type]
if proc.retval:
string = proc.retval.cpp_type(value=True) + ' '
else:
string = 'void '
string = string + '(*' + self.name + ')'
string = string + '(' + c_arg_list(proc,bind=True) + ')'
return string
else:
raise FWTypeException(self.type.type)
class Procedure(object):
def __init__(self,name,args,method,retval=None,comment=None,nopass=False):
self.name = name
self.args = args # By name
self.method = method # None, 't' (TYPE), 'c' (CLASS)
self.retval = retval
self.comment = comment
self.nopass = nopass
self.nargs = len(args)
self.module = current_module
self.num = module_proc_num
self.tbp = None
self.ctor = False
self.dtor = False
self.in_orphan_class = False # Set in associate_procedures
if self.method and not nopass:
if ctor_def.match(name):
self.ctor = True
elif dtor_def.match(name) and self.valid_dtor():
self.dtor = True
# Check for exclusion:
for arg in args.values():
if (name.lower(),arg.name.lower()) in proc_arg_exclusions:
if arg.optional:
arg.exclude = True
else:
warning("Argument exclusions only valid for optional arguments: " + name + ', ' + arg.name)
# Make ordered argument list
self.arglist = sorted(self.args.values(), key=lambda arg: arg.pos)
# Check for arguments that can have default values of NULL in C++
for arg in reversed(self.arglist):
# (Assumes the dictionary iteration order is sorted by key)
if arg.optional:
arg.cpp_optional = True
else:
break
self.add_hidden_strlen_args()
# Check for integer arguments that define array sizes:
for arg in self.args.values():
if arg.type.type.upper()=='INTEGER' and arg.intent=='in':
if not opts.no_vector and self.get_vec_size_parent(arg.name):
# The check on opts.no_vector prevents writing
# wrapper code that tries to extract the array
# size from a C array
arg.type.is_array_size = True
elif not opts.no_fmat and self.get_matrix_size_parent(arg.name):
arg.type.is_matrix_size = True
def has_args_past_pos(self,ipos,bind):
"""Query whether or not the argument list continues past pos,
accounting for c++ optional args
ipos - 0-indexed argument position"""
has = False
for i,arg in enumerate(self.arglist):
if i > ipos:
if not arg.fort_only():
has = True
elif bind:
has = True
return has
def add_hidden_strlen_args(self):
"""Add Fortran-only string length arguments to end of argument list"""
nargs = len(self.args)
pos = nargs
for arg in self.arglist:
if arg.type.type=='CHARACTER' and not arg.fort_only():
str_length_arg = Argument(arg.name + '_len__', pos, DataType('INT', str_len=arg.type.str_len ,hidden=True))
self.args[ str_length_arg.name ] = str_length_arg
self.arglist.append(str_length_arg)
pos = pos + 1
def get_vec_size_parent(self,argname):
"""Get the first 1d array argument that uses the argument argname to
define its size"""
for arg in self.arglist:
if arg.type.vec and not arg.optional and arg.type.array.size_var==argname:
return arg.name
return None
def get_matrix_size_parent(self,argname):
"""Similar to get_vec_size_parent. Returns (matname,0) if argname
is the number of rows and (matname,1) if argname is the number of
columns"""
for arg in self.arglist:
if arg.type.matrix and not arg.optional and argname in arg.type.array.size_var:
if argname == arg.type.array.size_var[0]:
return arg.name,0
else:
return arg.name,1
return None
def has_post_call_wrapper_code(self):
"""Whether or not wrapper code will be needed for after the call to
the Fortran procedure"""
for arg in self.args.values():
# Special string handling for after the call needed
if arg.type.type=='CHARACTER' and not arg.fort_only() and arg.intent=='out':
return True
return False
def valid_dtor(self):
"""Whether the procedure is a valid dtor. Mainly this just
checks that there are no required arguments"""
for arg in self.args.values():
if arg.pos > 0 and not arg.optional:
return False
return True
class DerivedType(object):
def __init__(self,name,comment=None):
self.name = name
self.cname = translate_name(name) # Account for name renaming
self.procs = []
self.module = current_module
self.comment = comment
self.pointer_return_types = set() # Objects that methods of this type can return using pointers
self.has_pointer_ctor = False
self.is_class = False
self.abstract = False
self.extends = None
self.tbps = dict() # lowercase procname => tbp instance
def add_tbp(self, tbp):
self.tbps[tbp.procname.lower()] = tbp
def ctor_list(self):
"""Return list of associated ctors"""
ctors = []
for proc in self.procs:
if proc.ctor:
ctors.append(proc)
return ctors
def get_pointer_return_types(self):
for proc in self.procs:
if proc.retval and proc.retval.pointer and proc.retval.type.dt and proc.retval.type.type.lower() in objects and proc.retval.type.type.lower() != self.name.lower():
self.pointer_return_types.add(proc.retval.type.type)
class TypeBoundProcedure(object):
def __init__(self, name, procname, interface, deferred, nopass):
global current_module, nopass_tbps
self.name = name
self.procname = procname
# Initially False or a string, but the string gets changed to
# a procedure instance in associate_procedures
self.interface = interface
self.deferred = deferred
self.nopass = nopass
if nopass:
nopass_tbps[current_module.lower(), procname.lower()] = self
def mangle_name(mod,func):
if mod:
if compiler == 'g95':
return mod.lower() + "_MP_" + func.lower()
else: # gfortran
return '__' + mod.lower() + '_MOD_' + func.lower()
else:
suffix = '_'
if compiler=='g95' and '_' in func:
suffix = suffix + '_'
return func.lower() + suffix
def vtab_symbol(mod,name):
return '__{0}_MOD___vtab_{0}_{1}'.format(mod.lower(), name.capitalize())
def get_proc(name):
"""Return the first procedure in the global list that matches name"""
for proc in procedures:
if proc.name.lower()==name.lower():
return proc
return None
def remove_const(argtype):
"""Remove const from argtype"""
if argtype.startswith('const'):
return argtype.split('const ')[1]
return argtype
def translate_name(name):
"""Use a substitution dictionary followed by a list of replacement patterns to translate the provided name, or return the input unchanged if no matches are found"""
if name.lower() in name_substitutions:
return name_substitutions[name.lower()]
else:
for pattern,replacement in pattern_substitutions:
name = pattern.sub(replacement,name)
return name
class FileReader:
"""Wrapper around file that provides facilities for backing up"""
def __init__(self, fname):
try:
with open(fname, 'r') as f:
self.file_lines_list = f.readlines()
except IOError:
error("Error opening file " + fname)
self.file_lines_list = None
self.success = False
else:
self.file_pointer = 0
self.success = True
# Note on reading and joining lines. Did try automatically
# calling join_lines inside readlines (with exception within
# parse_comments), but that can fail for certain cases with string
# continuations, which aren't handled correctly due to the second
# "&". A string continuation at the right place (e.g. right
# before the end of a procedure) would cause the resulting parsing
# to fail.
def readline(self):
"""Acts like readline, but grabs the line out of a global list. This
way can move backwards in the list
"""
if self.file_pointer < len(self.file_lines_list):
self.file_pointer += 1
return self.file_lines_list[self.file_pointer-1]
else:
return ''
def join_lines(self, line):
"""Join lines possibly continued by & character"""
while '&' in line.split('!')[0]:
line1 = line.split('&')[0]
line2 = self.readline()
line = line1 + line2.strip()
return line
def parse_comments(self,line):
"""
Parse doxygen comments. On inline comments, return file back to
line containing comment start.
"""
#print "Parsing comment:", line
com = []
read_count = 0
if fort_dox_comments.match(line):
com.append(line.split('!>')[1].strip())
elif fort_dox_inline.match(line):
com.append(line.split('!<')[1].strip())
else:
warning("Bad line in parse_comments: " + line)
while True:
line = self.readline().strip()
if line.startswith('!!'):
text = line.split('!!')[1]
# Preserve whitespace indentation:
if text.startswith(' '):
text = text[1:]
com.append(text)
read_count+=1
else:
# Back up a line, or all the way back to the comment start
# if it is inline
if fort_dox_inline.match(line):
for i in range(read_count):
self.file_pointer -= 1
self.file_pointer -= 1
break
return com
def is_public(name):
"""Check whether a name is public and not excluded
The private/public parts of this check rely on global variables
that are updated while the Fortran source is processed, so this
function should only be called during the parsing portion (not
during code generation, after parsing is finished)
"""
if name.lower() in name_exclusions:
return False
elif name.lower() in name_inclusions:
return True
elif default_protection == PUBLIC:
return not name.lower() in private_names
else:
return name.lower() in public_names
# TODO: delete if not being used
def args_have_comment(args):
"""Whether or not there are any comments in a set of arguments"""
for arg in args.values():
if arg.comment:
return True
return False
def add_type(t):
if is_public(t):
objects[t.lower()] = DerivedType(t,dox_comments)
return True
else:
return False
def parse_argument_defs(line,file,arg_list_lower,args,retval,comments):
global proc_pointer_used
count = 0
line = file.join_lines(line)
line = line.split('!')[0]
m = fort_data_def.match(line)
attributes = m.group('attributes')
# Attributes.
if not attributes:
# Change None to string so searching works
attributes = ''
optional = True if optional_def.search(attributes) else False
byval = True if byval_def.search(attributes) else False
allocatable = True if allocatable_def.search(attributes) else False
pointer = True if fort_pointer_def.search(attributes) else False
# Check for DIMENSION statement
dimension = dimension_def.search(attributes)
intent = 'inout'
if intent_in_def.match(attributes):
intent = 'in'
elif intent_out_def.match(attributes):
intent = 'out'
# Get type string [e.g. INTEGER, TYPE(ErrorType),
# PROCEDURE(template), POINTER]
type_string = m.group(1)
# Process character length
char_len = None
if type_string.upper().startswith('CHARACTER'):
type_string = 'CHARACTER'
if m.group('old_kind_spec'):
char_len = int( m.group('old_kind_spec') )
elif m.group('kind_spec'):
spec = m.group('kind_spec')
if spec == '*':
char_len = '*'
else:
try:
char_len = int(spec)
except ValueError:
# Check for string in Fortran parameter
# dictionary. Note, this conversion/check could
# be done later when writing the wrapper code (so
# that all source has been parsed): in that case,
# make sure have proper checks so that it doesn't
# conflict with treatment of assumed length
# strings
char_len = fort_integer_params.get(spec.upper(), None)
else:
# No char length spec found. Could use this to wrap
# scalar CHARACTER
char_len = None # Redundant
char_len = CharacterLength(char_len)
# Get name(s)
arg_string = line.split('::')[1].split('!')[0]
names = [name.strip() for name in arg_splitter.split(arg_string)]
for name in names:
array = None
if dimension:
array = Array(dimension.group(1))
elif '(' in name:
size_desc = name.split('(')[1].split(')')[0]
array = Array(size_desc)
name = name.split('(')[0]
type = DataType(type_string,array,char_len)
if type.proc and pointer:
type.proc = False
type.proc_pointer = True
proc_pointer_used = True
if name.lower() in arg_list_lower:
count += 1
if char_len and char_len.val=='*':
# Assign a new char_len instance and set it to contain
# a reference to the argument name, which will be
# needed in the wrapper code
type.str_len = CharacterLength('*')
type.str_len.set_assumed(name)
args[name] = Argument(name,arg_list_lower.index(name.lower()),type,optional,intent,byval,allocatable,pointer,comment=comments)
elif retval and name.lower()==retval.name.lower():
retval.set_type(type)
retval.pointer = pointer
retval.comment = comments
return count
def parse_proc(file,line,abstract=False):
"""
Parse a procedure definition, given starting line
"""
global dox_comments, abstract_interfaces, module_proc_num, not_wrapped
# Store in case decide to overwrite them when parsing arg comments
proc_comments = dox_comments
# First check for line continuation:
line = file.join_lines(line)
proc_name = line.split('(')[0].split()[-1]
arg_string = line.split('(')[1].split(')')[0]
if re.search(r'\S',arg_string):
arg_list_lower = arg_string.split(',')
arg_list_lower = [x.strip().lower() for x in arg_list_lower] # Remove whitespace and convert to lowercase
else:
arg_list_lower = []
args = dict()
#print arg_list_lower
retval = None
if re.match('^\s*function', line, re.IGNORECASE):
m = result_name_def.match(line)
if m:
retval = Argument(m.group(1), None) # pos not used
else:
retval = Argument(proc_name, None) # pos not used
# Determine argument types
method = False
invalid = False
arg_comments = []
while True:
line = file.readline()
if not line:
error("Unexpected end of file parsing procedure '{}'".format(proc_name))
return
elif fort_end_proc.match(line):
break
elif fort_proc_def.match(line):
# This means we found a contained procedure. We need to
# parse through it to the end to make sure that its
# arguments don't overwrite the parent's arguments, and
# that we don't wrap the contained procedure itself
while True:
line = file.readline()
if not line:
error("Unexpected end of file parsing contained procedure within '{}'".format(proc_name))
return
elif fort_end_proc.match(line):
break
elif fort_contains.match(line):
in_contains = True
elif fort_dox_comments.match(line):
arg_comments = file.parse_comments(line)
continue
elif fort_dox_inline.match(line):
# Note: don't CONTINUE here b/c still need to parse this arg
arg_comments = file.parse_comments(line)
elif fort_comment.match(line):
continue
if fort_data_def.match(line):
# Could check below return value to see if in local
# variables (assuming definitions are ordered in code)
parse_argument_defs(line,file,arg_list_lower,args,retval,arg_comments)
arg_comments = []
elif fort_class_data_def.match(line):
warning("CLASS arguments not currently supported: " + proc_name)
# Check args:
if len(args) != len(arg_list_lower):
missing_args = set(arg_list_lower).difference(set(args.keys()))
error("Missing argument definitions in procedure {}: {}".format(proc_name, ', '.join(missing_args)))
invalid = True
for arg in args.values():
if arg.fort_only() and not arg.optional:
# Note: the above fort_only() call depends on the
# appropriate abstract interfaces already having been
# defined. Make sure the Fortran source file that
# contains those definitions is parsed first
invalid = True
if arg.pos==0 and arg.type.dt:
method = True
arg.is_self_arg = True
if retval:
if retval.type:
if retval.type.array:
invalid = True
elif retval.type.type == 'CHARACTER':
invalid = True
elif retval.type.dt:
if not retval.pointer:
invalid = True
elif not retval.type.valid_primitive():
invalid = True
else:
error("Untyped return value in {}: {}".format(proc_name,retval.name))
invalid = True
if invalid:
not_wrapped.append(proc_name)
else:
is_tbp = False
nopass = False
if not method:
if (current_module.lower(), proc_name.lower()) in nopass_tbps:
is_tbp = True
method = True
nopass = True
proc = Procedure(proc_name,args,method,retval,proc_comments,nopass)
if method and not nopass:
try:
if proc_name.lower() in objects[proc.arglist[0].type.type.lower()].tbps:
is_tbp = True
except KeyError:
# Should mean that the derived type is not public
pass
# Note: wrap all abstract procedures (even if they are not
# public). This is sort of a hack, as technically we should
# only wrap non-public abstract procedures if they are used in
# TBP definitions
if is_public(proc_name) or is_tbp or abstract:
if not abstract:
procedures.append(proc)
module_proc_num += 1
else:
abstract_interfaces[proc_name] = proc
def parse_abstract_interface(file,line):
global dox_comments
while True:
line = file.readline()
if line=='':
print("Unexpected end of file in abstract interface")
return
elif fort_dox_comments.match(line):
# Grab comments and ignore them
dox_comments = file.parse_comments(line)
continue
elif fort_end_interface.match(line):
break
elif fort_comment.match(line):
continue
elif fort_proc_def.match(line):
parse_proc(file,line,abstract=True)
dox_comments = []
def parse_type(file,line):
global fort_class_used
m = fort_type_def.match(line)
typename = m.group('name0') or m.group('name1')
type_added = add_type(typename)
# type_added checks below prevent KeyError's in objects[]
if type_added and 'ABSTRACT' in line.upper():
objects[typename.lower()].abstract = True
objects[typename.lower()].is_class = True
fort_class_used = True
extends_match = fort_type_extends_def.search(line)
if type_added and extends_match:
objects[typename.lower()].extends = extends_match.group(1)
objects[typename.lower()].is_class = True
fort_class_used = True
# if type_added:
# print "{} extends: {}".format(typename, objects[typename.lower()].extends)
# Move to end of type and parse type bound procedure definitions
while True:
line = file.readline()
line = file.join_lines(line)
if line == '':