applied-ai-018 commited on
Commit
35c5ae1
·
verified ·
1 Parent(s): df8ab07

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/numpy/f2py/capi_maps.py +819 -0
  2. llmeval-env/lib/python3.10/site-packages/numpy/f2py/crackfortran.py +0 -0
  3. llmeval-env/lib/python3.10/site-packages/numpy/f2py/symbolic.py +1517 -0
  4. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_callback.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_compile_function.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_docs.cpython-310.pyc +0 -0
  7. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_mixed.cpython-310.pyc +0 -0
  8. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_regression.cpython-310.pyc +0 -0
  9. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_return_logical.cpython-310.pyc +0 -0
  10. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_semicolon_split.cpython-310.pyc +0 -0
  11. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_size.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  13. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  14. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +230 -0
  15. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  16. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  17. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  18. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  19. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  20. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  21. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/foo.f +62 -0
  22. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  23. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  24. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh25211.f +10 -0
  25. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  26. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  27. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/cli/hi77.f +3 -0
  28. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  29. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/common/block.f +11 -0
  30. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  31. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  32. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  33. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  34. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  35. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  36. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  37. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  38. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  39. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/kind/foo.f90 +20 -0
  40. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/mixed/foo.f +5 -0
  41. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  42. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  43. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/module_data/mod.mod +0 -0
  44. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/module_data/module_data_docstring.f90 +12 -0
  45. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  46. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  47. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/regression/gh25337/data.f90 +8 -0
  48. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/regression/gh25337/use_data.f90 +6 -0
  49. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/regression/inout.f90 +9 -0
  50. llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/return_complex/foo77.f +45 -0
llmeval-env/lib/python3.10/site-packages/numpy/f2py/capi_maps.py ADDED
@@ -0,0 +1,819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
3
+ Copyright 2011 -- present NumPy Developers.
4
+ Permission to use, modify, and distribute this software is given under the
5
+ terms of the NumPy License.
6
+
7
+ NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
8
+ """
9
+ from . import __version__
10
+ f2py_version = __version__.version
11
+
12
+ import copy
13
+ import re
14
+ import os
15
+ from .crackfortran import markoutercomma
16
+ from . import cb_rules
17
+ from ._isocbind import iso_c_binding_map, isoc_c2pycode_map, iso_c2py_map
18
+
19
+ # The environment provided by auxfuncs.py is needed for some calls to eval.
20
+ # As the needed functions cannot be determined by static inspection of the
21
+ # code, it is safest to use import * pending a major refactoring of f2py.
22
+ from .auxfuncs import *
23
+
24
+ __all__ = [
25
+ 'getctype', 'getstrlength', 'getarrdims', 'getpydocsign',
26
+ 'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map',
27
+ 'cb_sign2map', 'cb_routsign2map', 'common_sign2map', 'process_f2cmap_dict'
28
+ ]
29
+
30
+
31
+ depargs = []
32
+ lcb_map = {}
33
+ lcb2_map = {}
34
+ # forced casting: mainly caused by the fact that Python or Numeric
35
+ # C/APIs do not support the corresponding C types.
36
+ c2py_map = {'double': 'float',
37
+ 'float': 'float', # forced casting
38
+ 'long_double': 'float', # forced casting
39
+ 'char': 'int', # forced casting
40
+ 'signed_char': 'int', # forced casting
41
+ 'unsigned_char': 'int', # forced casting
42
+ 'short': 'int', # forced casting
43
+ 'unsigned_short': 'int', # forced casting
44
+ 'int': 'int', # forced casting
45
+ 'long': 'int',
46
+ 'long_long': 'long',
47
+ 'unsigned': 'int', # forced casting
48
+ 'complex_float': 'complex', # forced casting
49
+ 'complex_double': 'complex',
50
+ 'complex_long_double': 'complex', # forced casting
51
+ 'string': 'string',
52
+ 'character': 'bytes',
53
+ }
54
+
55
+ c2capi_map = {'double': 'NPY_DOUBLE',
56
+ 'float': 'NPY_FLOAT',
57
+ 'long_double': 'NPY_LONGDOUBLE',
58
+ 'char': 'NPY_BYTE',
59
+ 'unsigned_char': 'NPY_UBYTE',
60
+ 'signed_char': 'NPY_BYTE',
61
+ 'short': 'NPY_SHORT',
62
+ 'unsigned_short': 'NPY_USHORT',
63
+ 'int': 'NPY_INT',
64
+ 'unsigned': 'NPY_UINT',
65
+ 'long': 'NPY_LONG',
66
+ 'unsigned_long': 'NPY_ULONG',
67
+ 'long_long': 'NPY_LONGLONG',
68
+ 'unsigned_long_long': 'NPY_ULONGLONG',
69
+ 'complex_float': 'NPY_CFLOAT',
70
+ 'complex_double': 'NPY_CDOUBLE',
71
+ 'complex_long_double': 'NPY_CDOUBLE',
72
+ 'string': 'NPY_STRING',
73
+ 'character': 'NPY_STRING'}
74
+
75
+ c2pycode_map = {'double': 'd',
76
+ 'float': 'f',
77
+ 'long_double': 'g',
78
+ 'char': 'b',
79
+ 'unsigned_char': 'B',
80
+ 'signed_char': 'b',
81
+ 'short': 'h',
82
+ 'unsigned_short': 'H',
83
+ 'int': 'i',
84
+ 'unsigned': 'I',
85
+ 'long': 'l',
86
+ 'unsigned_long': 'L',
87
+ 'long_long': 'q',
88
+ 'unsigned_long_long': 'Q',
89
+ 'complex_float': 'F',
90
+ 'complex_double': 'D',
91
+ 'complex_long_double': 'G',
92
+ 'string': 'S',
93
+ 'character': 'c'}
94
+
95
+ # https://docs.python.org/3/c-api/arg.html#building-values
96
+ c2buildvalue_map = {'double': 'd',
97
+ 'float': 'f',
98
+ 'char': 'b',
99
+ 'signed_char': 'b',
100
+ 'short': 'h',
101
+ 'int': 'i',
102
+ 'long': 'l',
103
+ 'long_long': 'L',
104
+ 'complex_float': 'N',
105
+ 'complex_double': 'N',
106
+ 'complex_long_double': 'N',
107
+ 'string': 'y',
108
+ 'character': 'c'}
109
+
110
+ f2cmap_all = {'real': {'': 'float', '4': 'float', '8': 'double',
111
+ '12': 'long_double', '16': 'long_double'},
112
+ 'integer': {'': 'int', '1': 'signed_char', '2': 'short',
113
+ '4': 'int', '8': 'long_long',
114
+ '-1': 'unsigned_char', '-2': 'unsigned_short',
115
+ '-4': 'unsigned', '-8': 'unsigned_long_long'},
116
+ 'complex': {'': 'complex_float', '8': 'complex_float',
117
+ '16': 'complex_double', '24': 'complex_long_double',
118
+ '32': 'complex_long_double'},
119
+ 'complexkind': {'': 'complex_float', '4': 'complex_float',
120
+ '8': 'complex_double', '12': 'complex_long_double',
121
+ '16': 'complex_long_double'},
122
+ 'logical': {'': 'int', '1': 'char', '2': 'short', '4': 'int',
123
+ '8': 'long_long'},
124
+ 'double complex': {'': 'complex_double'},
125
+ 'double precision': {'': 'double'},
126
+ 'byte': {'': 'char'},
127
+ }
128
+
129
+ # Add ISO_C handling
130
+ c2pycode_map.update(isoc_c2pycode_map)
131
+ c2py_map.update(iso_c2py_map)
132
+ f2cmap_all, _ = process_f2cmap_dict(f2cmap_all, iso_c_binding_map, c2py_map)
133
+ # End ISO_C handling
134
+ f2cmap_default = copy.deepcopy(f2cmap_all)
135
+
136
+ f2cmap_mapped = []
137
+
138
+ def load_f2cmap_file(f2cmap_file):
139
+ global f2cmap_all, f2cmap_mapped
140
+
141
+ f2cmap_all = copy.deepcopy(f2cmap_default)
142
+
143
+ if f2cmap_file is None:
144
+ # Default value
145
+ f2cmap_file = '.f2py_f2cmap'
146
+ if not os.path.isfile(f2cmap_file):
147
+ return
148
+
149
+ # User defined additions to f2cmap_all.
150
+ # f2cmap_file must contain a dictionary of dictionaries, only. For
151
+ # example, {'real':{'low':'float'}} means that Fortran 'real(low)' is
152
+ # interpreted as C 'float'. This feature is useful for F90/95 users if
153
+ # they use PARAMETERS in type specifications.
154
+ try:
155
+ outmess('Reading f2cmap from {!r} ...\n'.format(f2cmap_file))
156
+ with open(f2cmap_file) as f:
157
+ d = eval(f.read().lower(), {}, {})
158
+ f2cmap_all, f2cmap_mapped = process_f2cmap_dict(f2cmap_all, d, c2py_map, True)
159
+ outmess('Successfully applied user defined f2cmap changes\n')
160
+ except Exception as msg:
161
+ errmess('Failed to apply user defined f2cmap changes: %s. Skipping.\n' % (msg))
162
+
163
+
164
+ cformat_map = {'double': '%g',
165
+ 'float': '%g',
166
+ 'long_double': '%Lg',
167
+ 'char': '%d',
168
+ 'signed_char': '%d',
169
+ 'unsigned_char': '%hhu',
170
+ 'short': '%hd',
171
+ 'unsigned_short': '%hu',
172
+ 'int': '%d',
173
+ 'unsigned': '%u',
174
+ 'long': '%ld',
175
+ 'unsigned_long': '%lu',
176
+ 'long_long': '%ld',
177
+ 'complex_float': '(%g,%g)',
178
+ 'complex_double': '(%g,%g)',
179
+ 'complex_long_double': '(%Lg,%Lg)',
180
+ 'string': '\\"%s\\"',
181
+ 'character': "'%c'",
182
+ }
183
+
184
+ # Auxiliary functions
185
+
186
+
187
+ def getctype(var):
188
+ """
189
+ Determines C type
190
+ """
191
+ ctype = 'void'
192
+ if isfunction(var):
193
+ if 'result' in var:
194
+ a = var['result']
195
+ else:
196
+ a = var['name']
197
+ if a in var['vars']:
198
+ return getctype(var['vars'][a])
199
+ else:
200
+ errmess('getctype: function %s has no return value?!\n' % a)
201
+ elif issubroutine(var):
202
+ return ctype
203
+ elif ischaracter_or_characterarray(var):
204
+ return 'character'
205
+ elif isstring_or_stringarray(var):
206
+ return 'string'
207
+ elif 'typespec' in var and var['typespec'].lower() in f2cmap_all:
208
+ typespec = var['typespec'].lower()
209
+ f2cmap = f2cmap_all[typespec]
210
+ ctype = f2cmap[''] # default type
211
+ if 'kindselector' in var:
212
+ if '*' in var['kindselector']:
213
+ try:
214
+ ctype = f2cmap[var['kindselector']['*']]
215
+ except KeyError:
216
+ errmess('getctype: "%s %s %s" not supported.\n' %
217
+ (var['typespec'], '*', var['kindselector']['*']))
218
+ elif 'kind' in var['kindselector']:
219
+ if typespec + 'kind' in f2cmap_all:
220
+ f2cmap = f2cmap_all[typespec + 'kind']
221
+ try:
222
+ ctype = f2cmap[var['kindselector']['kind']]
223
+ except KeyError:
224
+ if typespec in f2cmap_all:
225
+ f2cmap = f2cmap_all[typespec]
226
+ try:
227
+ ctype = f2cmap[str(var['kindselector']['kind'])]
228
+ except KeyError:
229
+ errmess('getctype: "%s(kind=%s)" is mapped to C "%s" (to override define dict(%s = dict(%s="<C typespec>")) in %s/.f2py_f2cmap file).\n'
230
+ % (typespec, var['kindselector']['kind'], ctype,
231
+ typespec, var['kindselector']['kind'], os.getcwd()))
232
+ else:
233
+ if not isexternal(var):
234
+ errmess('getctype: No C-type found in "%s", assuming void.\n' % var)
235
+ return ctype
236
+
237
+
238
+ def f2cexpr(expr):
239
+ """Rewrite Fortran expression as f2py supported C expression.
240
+
241
+ Due to the lack of a proper expression parser in f2py, this
242
+ function uses a heuristic approach that assumes that Fortran
243
+ arithmetic expressions are valid C arithmetic expressions when
244
+ mapping Fortran function calls to the corresponding C function/CPP
245
+ macros calls.
246
+
247
+ """
248
+ # TODO: support Fortran `len` function with optional kind parameter
249
+ expr = re.sub(r'\blen\b', 'f2py_slen', expr)
250
+ return expr
251
+
252
+
253
+ def getstrlength(var):
254
+ if isstringfunction(var):
255
+ if 'result' in var:
256
+ a = var['result']
257
+ else:
258
+ a = var['name']
259
+ if a in var['vars']:
260
+ return getstrlength(var['vars'][a])
261
+ else:
262
+ errmess('getstrlength: function %s has no return value?!\n' % a)
263
+ if not isstring(var):
264
+ errmess(
265
+ 'getstrlength: expected a signature of a string but got: %s\n' % (repr(var)))
266
+ len = '1'
267
+ if 'charselector' in var:
268
+ a = var['charselector']
269
+ if '*' in a:
270
+ len = a['*']
271
+ elif 'len' in a:
272
+ len = f2cexpr(a['len'])
273
+ if re.match(r'\(\s*(\*|:)\s*\)', len) or re.match(r'(\*|:)', len):
274
+ if isintent_hide(var):
275
+ errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n' % (
276
+ repr(var)))
277
+ len = '-1'
278
+ return len
279
+
280
+
281
+ def getarrdims(a, var, verbose=0):
282
+ ret = {}
283
+ if isstring(var) and not isarray(var):
284
+ ret['size'] = getstrlength(var)
285
+ ret['rank'] = '0'
286
+ ret['dims'] = ''
287
+ elif isscalar(var):
288
+ ret['size'] = '1'
289
+ ret['rank'] = '0'
290
+ ret['dims'] = ''
291
+ elif isarray(var):
292
+ dim = copy.copy(var['dimension'])
293
+ ret['size'] = '*'.join(dim)
294
+ try:
295
+ ret['size'] = repr(eval(ret['size']))
296
+ except Exception:
297
+ pass
298
+ ret['dims'] = ','.join(dim)
299
+ ret['rank'] = repr(len(dim))
300
+ ret['rank*[-1]'] = repr(len(dim) * [-1])[1:-1]
301
+ for i in range(len(dim)): # solve dim for dependencies
302
+ v = []
303
+ if dim[i] in depargs:
304
+ v = [dim[i]]
305
+ else:
306
+ for va in depargs:
307
+ if re.match(r'.*?\b%s\b.*' % va, dim[i]):
308
+ v.append(va)
309
+ for va in v:
310
+ if depargs.index(va) > depargs.index(a):
311
+ dim[i] = '*'
312
+ break
313
+ ret['setdims'], i = '', -1
314
+ for d in dim:
315
+ i = i + 1
316
+ if d not in ['*', ':', '(*)', '(:)']:
317
+ ret['setdims'] = '%s#varname#_Dims[%d]=%s,' % (
318
+ ret['setdims'], i, d)
319
+ if ret['setdims']:
320
+ ret['setdims'] = ret['setdims'][:-1]
321
+ ret['cbsetdims'], i = '', -1
322
+ for d in var['dimension']:
323
+ i = i + 1
324
+ if d not in ['*', ':', '(*)', '(:)']:
325
+ ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
326
+ ret['cbsetdims'], i, d)
327
+ elif isintent_in(var):
328
+ outmess('getarrdims:warning: assumed shape array, using 0 instead of %r\n'
329
+ % (d))
330
+ ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
331
+ ret['cbsetdims'], i, 0)
332
+ elif verbose:
333
+ errmess(
334
+ 'getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n' % (repr(a), repr(d)))
335
+ if ret['cbsetdims']:
336
+ ret['cbsetdims'] = ret['cbsetdims'][:-1]
337
+ # if not isintent_c(var):
338
+ # var['dimension'].reverse()
339
+ return ret
340
+
341
+
342
+ def getpydocsign(a, var):
343
+ global lcb_map
344
+ if isfunction(var):
345
+ if 'result' in var:
346
+ af = var['result']
347
+ else:
348
+ af = var['name']
349
+ if af in var['vars']:
350
+ return getpydocsign(af, var['vars'][af])
351
+ else:
352
+ errmess('getctype: function %s has no return value?!\n' % af)
353
+ return '', ''
354
+ sig, sigout = a, a
355
+ opt = ''
356
+ if isintent_in(var):
357
+ opt = 'input'
358
+ elif isintent_inout(var):
359
+ opt = 'in/output'
360
+ out_a = a
361
+ if isintent_out(var):
362
+ for k in var['intent']:
363
+ if k[:4] == 'out=':
364
+ out_a = k[4:]
365
+ break
366
+ init = ''
367
+ ctype = getctype(var)
368
+
369
+ if hasinitvalue(var):
370
+ init, showinit = getinit(a, var)
371
+ init = ', optional\\n Default: %s' % showinit
372
+ if isscalar(var):
373
+ if isintent_inout(var):
374
+ sig = '%s : %s rank-0 array(%s,\'%s\')%s' % (a, opt, c2py_map[ctype],
375
+ c2pycode_map[ctype], init)
376
+ else:
377
+ sig = '%s : %s %s%s' % (a, opt, c2py_map[ctype], init)
378
+ sigout = '%s : %s' % (out_a, c2py_map[ctype])
379
+ elif isstring(var):
380
+ if isintent_inout(var):
381
+ sig = '%s : %s rank-0 array(string(len=%s),\'c\')%s' % (
382
+ a, opt, getstrlength(var), init)
383
+ else:
384
+ sig = '%s : %s string(len=%s)%s' % (
385
+ a, opt, getstrlength(var), init)
386
+ sigout = '%s : string(len=%s)' % (out_a, getstrlength(var))
387
+ elif isarray(var):
388
+ dim = var['dimension']
389
+ rank = repr(len(dim))
390
+ sig = '%s : %s rank-%s array(\'%s\') with bounds (%s)%s' % (a, opt, rank,
391
+ c2pycode_map[
392
+ ctype],
393
+ ','.join(dim), init)
394
+ if a == out_a:
395
+ sigout = '%s : rank-%s array(\'%s\') with bounds (%s)'\
396
+ % (a, rank, c2pycode_map[ctype], ','.join(dim))
397
+ else:
398
+ sigout = '%s : rank-%s array(\'%s\') with bounds (%s) and %s storage'\
399
+ % (out_a, rank, c2pycode_map[ctype], ','.join(dim), a)
400
+ elif isexternal(var):
401
+ ua = ''
402
+ if a in lcb_map and lcb_map[a] in lcb2_map and 'argname' in lcb2_map[lcb_map[a]]:
403
+ ua = lcb2_map[lcb_map[a]]['argname']
404
+ if not ua == a:
405
+ ua = ' => %s' % ua
406
+ else:
407
+ ua = ''
408
+ sig = '%s : call-back function%s' % (a, ua)
409
+ sigout = sig
410
+ else:
411
+ errmess(
412
+ 'getpydocsign: Could not resolve docsignature for "%s".\n' % a)
413
+ return sig, sigout
414
+
415
+
416
+ def getarrdocsign(a, var):
417
+ ctype = getctype(var)
418
+ if isstring(var) and (not isarray(var)):
419
+ sig = '%s : rank-0 array(string(len=%s),\'c\')' % (a,
420
+ getstrlength(var))
421
+ elif isscalar(var):
422
+ sig = '%s : rank-0 array(%s,\'%s\')' % (a, c2py_map[ctype],
423
+ c2pycode_map[ctype],)
424
+ elif isarray(var):
425
+ dim = var['dimension']
426
+ rank = repr(len(dim))
427
+ sig = '%s : rank-%s array(\'%s\') with bounds (%s)' % (a, rank,
428
+ c2pycode_map[
429
+ ctype],
430
+ ','.join(dim))
431
+ return sig
432
+
433
+
434
+ def getinit(a, var):
435
+ if isstring(var):
436
+ init, showinit = '""', "''"
437
+ else:
438
+ init, showinit = '', ''
439
+ if hasinitvalue(var):
440
+ init = var['=']
441
+ showinit = init
442
+ if iscomplex(var) or iscomplexarray(var):
443
+ ret = {}
444
+
445
+ try:
446
+ v = var["="]
447
+ if ',' in v:
448
+ ret['init.r'], ret['init.i'] = markoutercomma(
449
+ v[1:-1]).split('@,@')
450
+ else:
451
+ v = eval(v, {}, {})
452
+ ret['init.r'], ret['init.i'] = str(v.real), str(v.imag)
453
+ except Exception:
454
+ raise ValueError(
455
+ 'getinit: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a))
456
+ if isarray(var):
457
+ init = '(capi_c.r=%s,capi_c.i=%s,capi_c)' % (
458
+ ret['init.r'], ret['init.i'])
459
+ elif isstring(var):
460
+ if not init:
461
+ init, showinit = '""', "''"
462
+ if init[0] == "'":
463
+ init = '"%s"' % (init[1:-1].replace('"', '\\"'))
464
+ if init[0] == '"':
465
+ showinit = "'%s'" % (init[1:-1])
466
+ return init, showinit
467
+
468
+
469
+ def get_elsize(var):
470
+ if isstring(var) or isstringarray(var):
471
+ elsize = getstrlength(var)
472
+ # override with user-specified length when available:
473
+ elsize = var['charselector'].get('f2py_len', elsize)
474
+ return elsize
475
+ if ischaracter(var) or ischaracterarray(var):
476
+ return '1'
477
+ # for numerical types, PyArray_New* functions ignore specified
478
+ # elsize, so we just return 1 and let elsize be determined at
479
+ # runtime, see fortranobject.c
480
+ return '1'
481
+
482
+
483
+ def sign2map(a, var):
484
+ """
485
+ varname,ctype,atype
486
+ init,init.r,init.i,pytype
487
+ vardebuginfo,vardebugshowvalue,varshowvalue
488
+ varrformat
489
+
490
+ intent
491
+ """
492
+ out_a = a
493
+ if isintent_out(var):
494
+ for k in var['intent']:
495
+ if k[:4] == 'out=':
496
+ out_a = k[4:]
497
+ break
498
+ ret = {'varname': a, 'outvarname': out_a, 'ctype': getctype(var)}
499
+ intent_flags = []
500
+ for f, s in isintent_dict.items():
501
+ if f(var):
502
+ intent_flags.append('F2PY_%s' % s)
503
+ if intent_flags:
504
+ # TODO: Evaluate intent_flags here.
505
+ ret['intent'] = '|'.join(intent_flags)
506
+ else:
507
+ ret['intent'] = 'F2PY_INTENT_IN'
508
+ if isarray(var):
509
+ ret['varrformat'] = 'N'
510
+ elif ret['ctype'] in c2buildvalue_map:
511
+ ret['varrformat'] = c2buildvalue_map[ret['ctype']]
512
+ else:
513
+ ret['varrformat'] = 'O'
514
+ ret['init'], ret['showinit'] = getinit(a, var)
515
+ if hasinitvalue(var) and iscomplex(var) and not isarray(var):
516
+ ret['init.r'], ret['init.i'] = markoutercomma(
517
+ ret['init'][1:-1]).split('@,@')
518
+ if isexternal(var):
519
+ ret['cbnamekey'] = a
520
+ if a in lcb_map:
521
+ ret['cbname'] = lcb_map[a]
522
+ ret['maxnofargs'] = lcb2_map[lcb_map[a]]['maxnofargs']
523
+ ret['nofoptargs'] = lcb2_map[lcb_map[a]]['nofoptargs']
524
+ ret['cbdocstr'] = lcb2_map[lcb_map[a]]['docstr']
525
+ ret['cblatexdocstr'] = lcb2_map[lcb_map[a]]['latexdocstr']
526
+ else:
527
+ ret['cbname'] = a
528
+ errmess('sign2map: Confused: external %s is not in lcb_map%s.\n' % (
529
+ a, list(lcb_map.keys())))
530
+ if isstring(var):
531
+ ret['length'] = getstrlength(var)
532
+ if isarray(var):
533
+ ret = dictappend(ret, getarrdims(a, var))
534
+ dim = copy.copy(var['dimension'])
535
+ if ret['ctype'] in c2capi_map:
536
+ ret['atype'] = c2capi_map[ret['ctype']]
537
+ ret['elsize'] = get_elsize(var)
538
+ # Debug info
539
+ if debugcapi(var):
540
+ il = [isintent_in, 'input', isintent_out, 'output',
541
+ isintent_inout, 'inoutput', isrequired, 'required',
542
+ isoptional, 'optional', isintent_hide, 'hidden',
543
+ iscomplex, 'complex scalar',
544
+ l_and(isscalar, l_not(iscomplex)), 'scalar',
545
+ isstring, 'string', isarray, 'array',
546
+ iscomplexarray, 'complex array', isstringarray, 'string array',
547
+ iscomplexfunction, 'complex function',
548
+ l_and(isfunction, l_not(iscomplexfunction)), 'function',
549
+ isexternal, 'callback',
550
+ isintent_callback, 'callback',
551
+ isintent_aux, 'auxiliary',
552
+ ]
553
+ rl = []
554
+ for i in range(0, len(il), 2):
555
+ if il[i](var):
556
+ rl.append(il[i + 1])
557
+ if isstring(var):
558
+ rl.append('slen(%s)=%s' % (a, ret['length']))
559
+ if isarray(var):
560
+ ddim = ','.join(
561
+ map(lambda x, y: '%s|%s' % (x, y), var['dimension'], dim))
562
+ rl.append('dims(%s)' % ddim)
563
+ if isexternal(var):
564
+ ret['vardebuginfo'] = 'debug-capi:%s=>%s:%s' % (
565
+ a, ret['cbname'], ','.join(rl))
566
+ else:
567
+ ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % (
568
+ ret['ctype'], a, ret['showinit'], ','.join(rl))
569
+ if isscalar(var):
570
+ if ret['ctype'] in cformat_map:
571
+ ret['vardebugshowvalue'] = 'debug-capi:%s=%s' % (
572
+ a, cformat_map[ret['ctype']])
573
+ if isstring(var):
574
+ ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
575
+ a, a)
576
+ if isexternal(var):
577
+ ret['vardebugshowvalue'] = 'debug-capi:%s=%%p' % (a)
578
+ if ret['ctype'] in cformat_map:
579
+ ret['varshowvalue'] = '#name#:%s=%s' % (a, cformat_map[ret['ctype']])
580
+ ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
581
+ if isstring(var):
582
+ ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a)
583
+ ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
584
+ if hasnote(var):
585
+ ret['note'] = var['note']
586
+ return ret
587
+
588
+
589
+ def routsign2map(rout):
590
+ """
591
+ name,NAME,begintitle,endtitle
592
+ rname,ctype,rformat
593
+ routdebugshowvalue
594
+ """
595
+ global lcb_map
596
+ name = rout['name']
597
+ fname = getfortranname(rout)
598
+ ret = {'name': name,
599
+ 'texname': name.replace('_', '\\_'),
600
+ 'name_lower': name.lower(),
601
+ 'NAME': name.upper(),
602
+ 'begintitle': gentitle(name),
603
+ 'endtitle': gentitle('end of %s' % name),
604
+ 'fortranname': fname,
605
+ 'FORTRANNAME': fname.upper(),
606
+ 'callstatement': getcallstatement(rout) or '',
607
+ 'usercode': getusercode(rout) or '',
608
+ 'usercode1': getusercode1(rout) or '',
609
+ }
610
+ if '_' in fname:
611
+ ret['F_FUNC'] = 'F_FUNC_US'
612
+ else:
613
+ ret['F_FUNC'] = 'F_FUNC'
614
+ if '_' in name:
615
+ ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC_US'
616
+ else:
617
+ ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC'
618
+ lcb_map = {}
619
+ if 'use' in rout:
620
+ for u in rout['use'].keys():
621
+ if u in cb_rules.cb_map:
622
+ for un in cb_rules.cb_map[u]:
623
+ ln = un[0]
624
+ if 'map' in rout['use'][u]:
625
+ for k in rout['use'][u]['map'].keys():
626
+ if rout['use'][u]['map'][k] == un[0]:
627
+ ln = k
628
+ break
629
+ lcb_map[ln] = un[1]
630
+ elif 'externals' in rout and rout['externals']:
631
+ errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n' % (
632
+ ret['name'], repr(rout['externals'])))
633
+ ret['callprotoargument'] = getcallprotoargument(rout, lcb_map) or ''
634
+ if isfunction(rout):
635
+ if 'result' in rout:
636
+ a = rout['result']
637
+ else:
638
+ a = rout['name']
639
+ ret['rname'] = a
640
+ ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
641
+ ret['ctype'] = getctype(rout['vars'][a])
642
+ if hasresultnote(rout):
643
+ ret['resultnote'] = rout['vars'][a]['note']
644
+ rout['vars'][a]['note'] = ['See elsewhere.']
645
+ if ret['ctype'] in c2buildvalue_map:
646
+ ret['rformat'] = c2buildvalue_map[ret['ctype']]
647
+ else:
648
+ ret['rformat'] = 'O'
649
+ errmess('routsign2map: no c2buildvalue key for type %s\n' %
650
+ (repr(ret['ctype'])))
651
+ if debugcapi(rout):
652
+ if ret['ctype'] in cformat_map:
653
+ ret['routdebugshowvalue'] = 'debug-capi:%s=%s' % (
654
+ a, cformat_map[ret['ctype']])
655
+ if isstringfunction(rout):
656
+ ret['routdebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
657
+ a, a)
658
+ if isstringfunction(rout):
659
+ ret['rlength'] = getstrlength(rout['vars'][a])
660
+ if ret['rlength'] == '-1':
661
+ errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n' % (
662
+ repr(rout['name'])))
663
+ ret['rlength'] = '10'
664
+ if hasnote(rout):
665
+ ret['note'] = rout['note']
666
+ rout['note'] = ['See elsewhere.']
667
+ return ret
668
+
669
+
670
+ def modsign2map(m):
671
+ """
672
+ modulename
673
+ """
674
+ if ismodule(m):
675
+ ret = {'f90modulename': m['name'],
676
+ 'F90MODULENAME': m['name'].upper(),
677
+ 'texf90modulename': m['name'].replace('_', '\\_')}
678
+ else:
679
+ ret = {'modulename': m['name'],
680
+ 'MODULENAME': m['name'].upper(),
681
+ 'texmodulename': m['name'].replace('_', '\\_')}
682
+ ret['restdoc'] = getrestdoc(m) or []
683
+ if hasnote(m):
684
+ ret['note'] = m['note']
685
+ ret['usercode'] = getusercode(m) or ''
686
+ ret['usercode1'] = getusercode1(m) or ''
687
+ if m['body']:
688
+ ret['interface_usercode'] = getusercode(m['body'][0]) or ''
689
+ else:
690
+ ret['interface_usercode'] = ''
691
+ ret['pymethoddef'] = getpymethoddef(m) or ''
692
+ if 'coutput' in m:
693
+ ret['coutput'] = m['coutput']
694
+ if 'f2py_wrapper_output' in m:
695
+ ret['f2py_wrapper_output'] = m['f2py_wrapper_output']
696
+ return ret
697
+
698
+
699
+ def cb_sign2map(a, var, index=None):
700
+ ret = {'varname': a}
701
+ ret['varname_i'] = ret['varname']
702
+ ret['ctype'] = getctype(var)
703
+ if ret['ctype'] in c2capi_map:
704
+ ret['atype'] = c2capi_map[ret['ctype']]
705
+ ret['elsize'] = get_elsize(var)
706
+ if ret['ctype'] in cformat_map:
707
+ ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
708
+ if isarray(var):
709
+ ret = dictappend(ret, getarrdims(a, var))
710
+ ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
711
+ if hasnote(var):
712
+ ret['note'] = var['note']
713
+ var['note'] = ['See elsewhere.']
714
+ return ret
715
+
716
+
717
+ def cb_routsign2map(rout, um):
718
+ """
719
+ name,begintitle,endtitle,argname
720
+ ctype,rctype,maxnofargs,nofoptargs,returncptr
721
+ """
722
+ ret = {'name': 'cb_%s_in_%s' % (rout['name'], um),
723
+ 'returncptr': ''}
724
+ if isintent_callback(rout):
725
+ if '_' in rout['name']:
726
+ F_FUNC = 'F_FUNC_US'
727
+ else:
728
+ F_FUNC = 'F_FUNC'
729
+ ret['callbackname'] = '%s(%s,%s)' \
730
+ % (F_FUNC,
731
+ rout['name'].lower(),
732
+ rout['name'].upper(),
733
+ )
734
+ ret['static'] = 'extern'
735
+ else:
736
+ ret['callbackname'] = ret['name']
737
+ ret['static'] = 'static'
738
+ ret['argname'] = rout['name']
739
+ ret['begintitle'] = gentitle(ret['name'])
740
+ ret['endtitle'] = gentitle('end of %s' % ret['name'])
741
+ ret['ctype'] = getctype(rout)
742
+ ret['rctype'] = 'void'
743
+ if ret['ctype'] == 'string':
744
+ ret['rctype'] = 'void'
745
+ else:
746
+ ret['rctype'] = ret['ctype']
747
+ if ret['rctype'] != 'void':
748
+ if iscomplexfunction(rout):
749
+ ret['returncptr'] = """
750
+ #ifdef F2PY_CB_RETURNCOMPLEX
751
+ return_value=
752
+ #endif
753
+ """
754
+ else:
755
+ ret['returncptr'] = 'return_value='
756
+ if ret['ctype'] in cformat_map:
757
+ ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
758
+ if isstringfunction(rout):
759
+ ret['strlength'] = getstrlength(rout)
760
+ if isfunction(rout):
761
+ if 'result' in rout:
762
+ a = rout['result']
763
+ else:
764
+ a = rout['name']
765
+ if hasnote(rout['vars'][a]):
766
+ ret['note'] = rout['vars'][a]['note']
767
+ rout['vars'][a]['note'] = ['See elsewhere.']
768
+ ret['rname'] = a
769
+ ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
770
+ if iscomplexfunction(rout):
771
+ ret['rctype'] = """
772
+ #ifdef F2PY_CB_RETURNCOMPLEX
773
+ #ctype#
774
+ #else
775
+ void
776
+ #endif
777
+ """
778
+ else:
779
+ if hasnote(rout):
780
+ ret['note'] = rout['note']
781
+ rout['note'] = ['See elsewhere.']
782
+ nofargs = 0
783
+ nofoptargs = 0
784
+ if 'args' in rout and 'vars' in rout:
785
+ for a in rout['args']:
786
+ var = rout['vars'][a]
787
+ if l_or(isintent_in, isintent_inout)(var):
788
+ nofargs = nofargs + 1
789
+ if isoptional(var):
790
+ nofoptargs = nofoptargs + 1
791
+ ret['maxnofargs'] = repr(nofargs)
792
+ ret['nofoptargs'] = repr(nofoptargs)
793
+ if hasnote(rout) and isfunction(rout) and 'result' in rout:
794
+ ret['routnote'] = rout['note']
795
+ rout['note'] = ['See elsewhere.']
796
+ return ret
797
+
798
+
799
+ def common_sign2map(a, var): # obsolute
800
+ ret = {'varname': a, 'ctype': getctype(var)}
801
+ if isstringarray(var):
802
+ ret['ctype'] = 'char'
803
+ if ret['ctype'] in c2capi_map:
804
+ ret['atype'] = c2capi_map[ret['ctype']]
805
+ ret['elsize'] = get_elsize(var)
806
+ if ret['ctype'] in cformat_map:
807
+ ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
808
+ if isarray(var):
809
+ ret = dictappend(ret, getarrdims(a, var))
810
+ elif isstring(var):
811
+ ret['size'] = getstrlength(var)
812
+ ret['rank'] = '1'
813
+ ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
814
+ if hasnote(var):
815
+ ret['note'] = var['note']
816
+ var['note'] = ['See elsewhere.']
817
+ # for strings this returns 0-rank but actually is 1-rank
818
+ ret['arrdocstr'] = getarrdocsign(a, var)
819
+ return ret
llmeval-env/lib/python3.10/site-packages/numpy/f2py/crackfortran.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/symbolic.py ADDED
@@ -0,0 +1,1517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fortran/C symbolic expressions
2
+
3
+ References:
4
+ - J3/21-007: Draft Fortran 202x. https://j3-fortran.org/doc/year/21/21-007.pdf
5
+
6
+ Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
7
+ Copyright 2011 -- present NumPy Developers.
8
+ Permission to use, modify, and distribute this software is given under the
9
+ terms of the NumPy License.
10
+
11
+ NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
12
+ """
13
+
14
+ # To analyze Fortran expressions to solve dimensions specifications,
15
+ # for instances, we implement a minimal symbolic engine for parsing
16
+ # expressions into a tree of expression instances. As a first
17
+ # instance, we care only about arithmetic expressions involving
18
+ # integers and operations like addition (+), subtraction (-),
19
+ # multiplication (*), division (Fortran / is Python //, Fortran // is
20
+ # concatenate), and exponentiation (**). In addition, .pyf files may
21
+ # contain C expressions that support here is implemented as well.
22
+ #
23
+ # TODO: support logical constants (Op.BOOLEAN)
24
+ # TODO: support logical operators (.AND., ...)
25
+ # TODO: support defined operators (.MYOP., ...)
26
+ #
27
+ __all__ = ['Expr']
28
+
29
+
30
+ import re
31
+ import warnings
32
+ from enum import Enum
33
+ from math import gcd
34
+
35
+
36
+ class Language(Enum):
37
+ """
38
+ Used as Expr.tostring language argument.
39
+ """
40
+ Python = 0
41
+ Fortran = 1
42
+ C = 2
43
+
44
+
45
+ class Op(Enum):
46
+ """
47
+ Used as Expr op attribute.
48
+ """
49
+ INTEGER = 10
50
+ REAL = 12
51
+ COMPLEX = 15
52
+ STRING = 20
53
+ ARRAY = 30
54
+ SYMBOL = 40
55
+ TERNARY = 100
56
+ APPLY = 200
57
+ INDEXING = 210
58
+ CONCAT = 220
59
+ RELATIONAL = 300
60
+ TERMS = 1000
61
+ FACTORS = 2000
62
+ REF = 3000
63
+ DEREF = 3001
64
+
65
+
66
+ class RelOp(Enum):
67
+ """
68
+ Used in Op.RELATIONAL expression to specify the function part.
69
+ """
70
+ EQ = 1
71
+ NE = 2
72
+ LT = 3
73
+ LE = 4
74
+ GT = 5
75
+ GE = 6
76
+
77
+ @classmethod
78
+ def fromstring(cls, s, language=Language.C):
79
+ if language is Language.Fortran:
80
+ return {'.eq.': RelOp.EQ, '.ne.': RelOp.NE,
81
+ '.lt.': RelOp.LT, '.le.': RelOp.LE,
82
+ '.gt.': RelOp.GT, '.ge.': RelOp.GE}[s.lower()]
83
+ return {'==': RelOp.EQ, '!=': RelOp.NE, '<': RelOp.LT,
84
+ '<=': RelOp.LE, '>': RelOp.GT, '>=': RelOp.GE}[s]
85
+
86
+ def tostring(self, language=Language.C):
87
+ if language is Language.Fortran:
88
+ return {RelOp.EQ: '.eq.', RelOp.NE: '.ne.',
89
+ RelOp.LT: '.lt.', RelOp.LE: '.le.',
90
+ RelOp.GT: '.gt.', RelOp.GE: '.ge.'}[self]
91
+ return {RelOp.EQ: '==', RelOp.NE: '!=',
92
+ RelOp.LT: '<', RelOp.LE: '<=',
93
+ RelOp.GT: '>', RelOp.GE: '>='}[self]
94
+
95
+
96
+ class ArithOp(Enum):
97
+ """
98
+ Used in Op.APPLY expression to specify the function part.
99
+ """
100
+ POS = 1
101
+ NEG = 2
102
+ ADD = 3
103
+ SUB = 4
104
+ MUL = 5
105
+ DIV = 6
106
+ POW = 7
107
+
108
+
109
+ class OpError(Exception):
110
+ pass
111
+
112
+
113
+ class Precedence(Enum):
114
+ """
115
+ Used as Expr.tostring precedence argument.
116
+ """
117
+ ATOM = 0
118
+ POWER = 1
119
+ UNARY = 2
120
+ PRODUCT = 3
121
+ SUM = 4
122
+ LT = 6
123
+ EQ = 7
124
+ LAND = 11
125
+ LOR = 12
126
+ TERNARY = 13
127
+ ASSIGN = 14
128
+ TUPLE = 15
129
+ NONE = 100
130
+
131
+
132
+ integer_types = (int,)
133
+ number_types = (int, float)
134
+
135
+
136
+ def _pairs_add(d, k, v):
137
+ # Internal utility method for updating terms and factors data.
138
+ c = d.get(k)
139
+ if c is None:
140
+ d[k] = v
141
+ else:
142
+ c = c + v
143
+ if c:
144
+ d[k] = c
145
+ else:
146
+ del d[k]
147
+
148
+
149
+ class ExprWarning(UserWarning):
150
+ pass
151
+
152
+
153
+ def ewarn(message):
154
+ warnings.warn(message, ExprWarning, stacklevel=2)
155
+
156
+
157
+ class Expr:
158
+ """Represents a Fortran expression as a op-data pair.
159
+
160
+ Expr instances are hashable and sortable.
161
+ """
162
+
163
+ @staticmethod
164
+ def parse(s, language=Language.C):
165
+ """Parse a Fortran expression to a Expr.
166
+ """
167
+ return fromstring(s, language=language)
168
+
169
+ def __init__(self, op, data):
170
+ assert isinstance(op, Op)
171
+
172
+ # sanity checks
173
+ if op is Op.INTEGER:
174
+ # data is a 2-tuple of numeric object and a kind value
175
+ # (default is 4)
176
+ assert isinstance(data, tuple) and len(data) == 2
177
+ assert isinstance(data[0], int)
178
+ assert isinstance(data[1], (int, str)), data
179
+ elif op is Op.REAL:
180
+ # data is a 2-tuple of numeric object and a kind value
181
+ # (default is 4)
182
+ assert isinstance(data, tuple) and len(data) == 2
183
+ assert isinstance(data[0], float)
184
+ assert isinstance(data[1], (int, str)), data
185
+ elif op is Op.COMPLEX:
186
+ # data is a 2-tuple of constant expressions
187
+ assert isinstance(data, tuple) and len(data) == 2
188
+ elif op is Op.STRING:
189
+ # data is a 2-tuple of quoted string and a kind value
190
+ # (default is 1)
191
+ assert isinstance(data, tuple) and len(data) == 2
192
+ assert (isinstance(data[0], str)
193
+ and data[0][::len(data[0])-1] in ('""', "''", '@@'))
194
+ assert isinstance(data[1], (int, str)), data
195
+ elif op is Op.SYMBOL:
196
+ # data is any hashable object
197
+ assert hash(data) is not None
198
+ elif op in (Op.ARRAY, Op.CONCAT):
199
+ # data is a tuple of expressions
200
+ assert isinstance(data, tuple)
201
+ assert all(isinstance(item, Expr) for item in data), data
202
+ elif op in (Op.TERMS, Op.FACTORS):
203
+ # data is {<term|base>:<coeff|exponent>} where dict values
204
+ # are nonzero Python integers
205
+ assert isinstance(data, dict)
206
+ elif op is Op.APPLY:
207
+ # data is (<function>, <operands>, <kwoperands>) where
208
+ # operands are Expr instances
209
+ assert isinstance(data, tuple) and len(data) == 3
210
+ # function is any hashable object
211
+ assert hash(data[0]) is not None
212
+ assert isinstance(data[1], tuple)
213
+ assert isinstance(data[2], dict)
214
+ elif op is Op.INDEXING:
215
+ # data is (<object>, <indices>)
216
+ assert isinstance(data, tuple) and len(data) == 2
217
+ # function is any hashable object
218
+ assert hash(data[0]) is not None
219
+ elif op is Op.TERNARY:
220
+ # data is (<cond>, <expr1>, <expr2>)
221
+ assert isinstance(data, tuple) and len(data) == 3
222
+ elif op in (Op.REF, Op.DEREF):
223
+ # data is Expr instance
224
+ assert isinstance(data, Expr)
225
+ elif op is Op.RELATIONAL:
226
+ # data is (<relop>, <left>, <right>)
227
+ assert isinstance(data, tuple) and len(data) == 3
228
+ else:
229
+ raise NotImplementedError(
230
+ f'unknown op or missing sanity check: {op}')
231
+
232
+ self.op = op
233
+ self.data = data
234
+
235
+ def __eq__(self, other):
236
+ return (isinstance(other, Expr)
237
+ and self.op is other.op
238
+ and self.data == other.data)
239
+
240
+ def __hash__(self):
241
+ if self.op in (Op.TERMS, Op.FACTORS):
242
+ data = tuple(sorted(self.data.items()))
243
+ elif self.op is Op.APPLY:
244
+ data = self.data[:2] + tuple(sorted(self.data[2].items()))
245
+ else:
246
+ data = self.data
247
+ return hash((self.op, data))
248
+
249
+ def __lt__(self, other):
250
+ if isinstance(other, Expr):
251
+ if self.op is not other.op:
252
+ return self.op.value < other.op.value
253
+ if self.op in (Op.TERMS, Op.FACTORS):
254
+ return (tuple(sorted(self.data.items()))
255
+ < tuple(sorted(other.data.items())))
256
+ if self.op is Op.APPLY:
257
+ if self.data[:2] != other.data[:2]:
258
+ return self.data[:2] < other.data[:2]
259
+ return tuple(sorted(self.data[2].items())) < tuple(
260
+ sorted(other.data[2].items()))
261
+ return self.data < other.data
262
+ return NotImplemented
263
+
264
+ def __le__(self, other): return self == other or self < other
265
+
266
+ def __gt__(self, other): return not (self <= other)
267
+
268
+ def __ge__(self, other): return not (self < other)
269
+
270
+ def __repr__(self):
271
+ return f'{type(self).__name__}({self.op}, {self.data!r})'
272
+
273
+ def __str__(self):
274
+ return self.tostring()
275
+
276
+ def tostring(self, parent_precedence=Precedence.NONE,
277
+ language=Language.Fortran):
278
+ """Return a string representation of Expr.
279
+ """
280
+ if self.op in (Op.INTEGER, Op.REAL):
281
+ precedence = (Precedence.SUM if self.data[0] < 0
282
+ else Precedence.ATOM)
283
+ r = str(self.data[0]) + (f'_{self.data[1]}'
284
+ if self.data[1] != 4 else '')
285
+ elif self.op is Op.COMPLEX:
286
+ r = ', '.join(item.tostring(Precedence.TUPLE, language=language)
287
+ for item in self.data)
288
+ r = '(' + r + ')'
289
+ precedence = Precedence.ATOM
290
+ elif self.op is Op.SYMBOL:
291
+ precedence = Precedence.ATOM
292
+ r = str(self.data)
293
+ elif self.op is Op.STRING:
294
+ r = self.data[0]
295
+ if self.data[1] != 1:
296
+ r = self.data[1] + '_' + r
297
+ precedence = Precedence.ATOM
298
+ elif self.op is Op.ARRAY:
299
+ r = ', '.join(item.tostring(Precedence.TUPLE, language=language)
300
+ for item in self.data)
301
+ r = '[' + r + ']'
302
+ precedence = Precedence.ATOM
303
+ elif self.op is Op.TERMS:
304
+ terms = []
305
+ for term, coeff in sorted(self.data.items()):
306
+ if coeff < 0:
307
+ op = ' - '
308
+ coeff = -coeff
309
+ else:
310
+ op = ' + '
311
+ if coeff == 1:
312
+ term = term.tostring(Precedence.SUM, language=language)
313
+ else:
314
+ if term == as_number(1):
315
+ term = str(coeff)
316
+ else:
317
+ term = f'{coeff} * ' + term.tostring(
318
+ Precedence.PRODUCT, language=language)
319
+ if terms:
320
+ terms.append(op)
321
+ elif op == ' - ':
322
+ terms.append('-')
323
+ terms.append(term)
324
+ r = ''.join(terms) or '0'
325
+ precedence = Precedence.SUM if terms else Precedence.ATOM
326
+ elif self.op is Op.FACTORS:
327
+ factors = []
328
+ tail = []
329
+ for base, exp in sorted(self.data.items()):
330
+ op = ' * '
331
+ if exp == 1:
332
+ factor = base.tostring(Precedence.PRODUCT,
333
+ language=language)
334
+ elif language is Language.C:
335
+ if exp in range(2, 10):
336
+ factor = base.tostring(Precedence.PRODUCT,
337
+ language=language)
338
+ factor = ' * '.join([factor] * exp)
339
+ elif exp in range(-10, 0):
340
+ factor = base.tostring(Precedence.PRODUCT,
341
+ language=language)
342
+ tail += [factor] * -exp
343
+ continue
344
+ else:
345
+ factor = base.tostring(Precedence.TUPLE,
346
+ language=language)
347
+ factor = f'pow({factor}, {exp})'
348
+ else:
349
+ factor = base.tostring(Precedence.POWER,
350
+ language=language) + f' ** {exp}'
351
+ if factors:
352
+ factors.append(op)
353
+ factors.append(factor)
354
+ if tail:
355
+ if not factors:
356
+ factors += ['1']
357
+ factors += ['/', '(', ' * '.join(tail), ')']
358
+ r = ''.join(factors) or '1'
359
+ precedence = Precedence.PRODUCT if factors else Precedence.ATOM
360
+ elif self.op is Op.APPLY:
361
+ name, args, kwargs = self.data
362
+ if name is ArithOp.DIV and language is Language.C:
363
+ numer, denom = [arg.tostring(Precedence.PRODUCT,
364
+ language=language)
365
+ for arg in args]
366
+ r = f'{numer} / {denom}'
367
+ precedence = Precedence.PRODUCT
368
+ else:
369
+ args = [arg.tostring(Precedence.TUPLE, language=language)
370
+ for arg in args]
371
+ args += [k + '=' + v.tostring(Precedence.NONE)
372
+ for k, v in kwargs.items()]
373
+ r = f'{name}({", ".join(args)})'
374
+ precedence = Precedence.ATOM
375
+ elif self.op is Op.INDEXING:
376
+ name = self.data[0]
377
+ args = [arg.tostring(Precedence.TUPLE, language=language)
378
+ for arg in self.data[1:]]
379
+ r = f'{name}[{", ".join(args)}]'
380
+ precedence = Precedence.ATOM
381
+ elif self.op is Op.CONCAT:
382
+ args = [arg.tostring(Precedence.PRODUCT, language=language)
383
+ for arg in self.data]
384
+ r = " // ".join(args)
385
+ precedence = Precedence.PRODUCT
386
+ elif self.op is Op.TERNARY:
387
+ cond, expr1, expr2 = [a.tostring(Precedence.TUPLE,
388
+ language=language)
389
+ for a in self.data]
390
+ if language is Language.C:
391
+ r = f'({cond}?{expr1}:{expr2})'
392
+ elif language is Language.Python:
393
+ r = f'({expr1} if {cond} else {expr2})'
394
+ elif language is Language.Fortran:
395
+ r = f'merge({expr1}, {expr2}, {cond})'
396
+ else:
397
+ raise NotImplementedError(
398
+ f'tostring for {self.op} and {language}')
399
+ precedence = Precedence.ATOM
400
+ elif self.op is Op.REF:
401
+ r = '&' + self.data.tostring(Precedence.UNARY, language=language)
402
+ precedence = Precedence.UNARY
403
+ elif self.op is Op.DEREF:
404
+ r = '*' + self.data.tostring(Precedence.UNARY, language=language)
405
+ precedence = Precedence.UNARY
406
+ elif self.op is Op.RELATIONAL:
407
+ rop, left, right = self.data
408
+ precedence = (Precedence.EQ if rop in (RelOp.EQ, RelOp.NE)
409
+ else Precedence.LT)
410
+ left = left.tostring(precedence, language=language)
411
+ right = right.tostring(precedence, language=language)
412
+ rop = rop.tostring(language=language)
413
+ r = f'{left} {rop} {right}'
414
+ else:
415
+ raise NotImplementedError(f'tostring for op {self.op}')
416
+ if parent_precedence.value < precedence.value:
417
+ # If parent precedence is higher than operand precedence,
418
+ # operand will be enclosed in parenthesis.
419
+ return '(' + r + ')'
420
+ return r
421
+
422
+ def __pos__(self):
423
+ return self
424
+
425
+ def __neg__(self):
426
+ return self * -1
427
+
428
+ def __add__(self, other):
429
+ other = as_expr(other)
430
+ if isinstance(other, Expr):
431
+ if self.op is other.op:
432
+ if self.op in (Op.INTEGER, Op.REAL):
433
+ return as_number(
434
+ self.data[0] + other.data[0],
435
+ max(self.data[1], other.data[1]))
436
+ if self.op is Op.COMPLEX:
437
+ r1, i1 = self.data
438
+ r2, i2 = other.data
439
+ return as_complex(r1 + r2, i1 + i2)
440
+ if self.op is Op.TERMS:
441
+ r = Expr(self.op, dict(self.data))
442
+ for k, v in other.data.items():
443
+ _pairs_add(r.data, k, v)
444
+ return normalize(r)
445
+ if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):
446
+ return self + as_complex(other)
447
+ elif self.op in (Op.INTEGER, Op.REAL) and other.op is Op.COMPLEX:
448
+ return as_complex(self) + other
449
+ elif self.op is Op.REAL and other.op is Op.INTEGER:
450
+ return self + as_real(other, kind=self.data[1])
451
+ elif self.op is Op.INTEGER and other.op is Op.REAL:
452
+ return as_real(self, kind=other.data[1]) + other
453
+ return as_terms(self) + as_terms(other)
454
+ return NotImplemented
455
+
456
+ def __radd__(self, other):
457
+ if isinstance(other, number_types):
458
+ return as_number(other) + self
459
+ return NotImplemented
460
+
461
+ def __sub__(self, other):
462
+ return self + (-other)
463
+
464
+ def __rsub__(self, other):
465
+ if isinstance(other, number_types):
466
+ return as_number(other) - self
467
+ return NotImplemented
468
+
469
+ def __mul__(self, other):
470
+ other = as_expr(other)
471
+ if isinstance(other, Expr):
472
+ if self.op is other.op:
473
+ if self.op in (Op.INTEGER, Op.REAL):
474
+ return as_number(self.data[0] * other.data[0],
475
+ max(self.data[1], other.data[1]))
476
+ elif self.op is Op.COMPLEX:
477
+ r1, i1 = self.data
478
+ r2, i2 = other.data
479
+ return as_complex(r1 * r2 - i1 * i2, r1 * i2 + r2 * i1)
480
+
481
+ if self.op is Op.FACTORS:
482
+ r = Expr(self.op, dict(self.data))
483
+ for k, v in other.data.items():
484
+ _pairs_add(r.data, k, v)
485
+ return normalize(r)
486
+ elif self.op is Op.TERMS:
487
+ r = Expr(self.op, {})
488
+ for t1, c1 in self.data.items():
489
+ for t2, c2 in other.data.items():
490
+ _pairs_add(r.data, t1 * t2, c1 * c2)
491
+ return normalize(r)
492
+
493
+ if self.op is Op.COMPLEX and other.op in (Op.INTEGER, Op.REAL):
494
+ return self * as_complex(other)
495
+ elif other.op is Op.COMPLEX and self.op in (Op.INTEGER, Op.REAL):
496
+ return as_complex(self) * other
497
+ elif self.op is Op.REAL and other.op is Op.INTEGER:
498
+ return self * as_real(other, kind=self.data[1])
499
+ elif self.op is Op.INTEGER and other.op is Op.REAL:
500
+ return as_real(self, kind=other.data[1]) * other
501
+
502
+ if self.op is Op.TERMS:
503
+ return self * as_terms(other)
504
+ elif other.op is Op.TERMS:
505
+ return as_terms(self) * other
506
+
507
+ return as_factors(self) * as_factors(other)
508
+ return NotImplemented
509
+
510
+ def __rmul__(self, other):
511
+ if isinstance(other, number_types):
512
+ return as_number(other) * self
513
+ return NotImplemented
514
+
515
+ def __pow__(self, other):
516
+ other = as_expr(other)
517
+ if isinstance(other, Expr):
518
+ if other.op is Op.INTEGER:
519
+ exponent = other.data[0]
520
+ # TODO: other kind not used
521
+ if exponent == 0:
522
+ return as_number(1)
523
+ if exponent == 1:
524
+ return self
525
+ if exponent > 0:
526
+ if self.op is Op.FACTORS:
527
+ r = Expr(self.op, {})
528
+ for k, v in self.data.items():
529
+ r.data[k] = v * exponent
530
+ return normalize(r)
531
+ return self * (self ** (exponent - 1))
532
+ elif exponent != -1:
533
+ return (self ** (-exponent)) ** -1
534
+ return Expr(Op.FACTORS, {self: exponent})
535
+ return as_apply(ArithOp.POW, self, other)
536
+ return NotImplemented
537
+
538
+ def __truediv__(self, other):
539
+ other = as_expr(other)
540
+ if isinstance(other, Expr):
541
+ # Fortran / is different from Python /:
542
+ # - `/` is a truncate operation for integer operands
543
+ return normalize(as_apply(ArithOp.DIV, self, other))
544
+ return NotImplemented
545
+
546
+ def __rtruediv__(self, other):
547
+ other = as_expr(other)
548
+ if isinstance(other, Expr):
549
+ return other / self
550
+ return NotImplemented
551
+
552
+ def __floordiv__(self, other):
553
+ other = as_expr(other)
554
+ if isinstance(other, Expr):
555
+ # Fortran // is different from Python //:
556
+ # - `//` is a concatenate operation for string operands
557
+ return normalize(Expr(Op.CONCAT, (self, other)))
558
+ return NotImplemented
559
+
560
+ def __rfloordiv__(self, other):
561
+ other = as_expr(other)
562
+ if isinstance(other, Expr):
563
+ return other // self
564
+ return NotImplemented
565
+
566
+ def __call__(self, *args, **kwargs):
567
+ # In Fortran, parenthesis () are use for both function call as
568
+ # well as indexing operations.
569
+ #
570
+ # TODO: implement a method for deciding when __call__ should
571
+ # return an INDEXING expression.
572
+ return as_apply(self, *map(as_expr, args),
573
+ **dict((k, as_expr(v)) for k, v in kwargs.items()))
574
+
575
+ def __getitem__(self, index):
576
+ # Provided to support C indexing operations that .pyf files
577
+ # may contain.
578
+ index = as_expr(index)
579
+ if not isinstance(index, tuple):
580
+ index = index,
581
+ if len(index) > 1:
582
+ ewarn(f'C-index should be a single expression but got `{index}`')
583
+ return Expr(Op.INDEXING, (self,) + index)
584
+
585
+ def substitute(self, symbols_map):
586
+ """Recursively substitute symbols with values in symbols map.
587
+
588
+ Symbols map is a dictionary of symbol-expression pairs.
589
+ """
590
+ if self.op is Op.SYMBOL:
591
+ value = symbols_map.get(self)
592
+ if value is None:
593
+ return self
594
+ m = re.match(r'\A(@__f2py_PARENTHESIS_(\w+)_\d+@)\Z', self.data)
595
+ if m:
596
+ # complement to fromstring method
597
+ items, paren = m.groups()
598
+ if paren in ['ROUNDDIV', 'SQUARE']:
599
+ return as_array(value)
600
+ assert paren == 'ROUND', (paren, value)
601
+ return value
602
+ if self.op in (Op.INTEGER, Op.REAL, Op.STRING):
603
+ return self
604
+ if self.op in (Op.ARRAY, Op.COMPLEX):
605
+ return Expr(self.op, tuple(item.substitute(symbols_map)
606
+ for item in self.data))
607
+ if self.op is Op.CONCAT:
608
+ return normalize(Expr(self.op, tuple(item.substitute(symbols_map)
609
+ for item in self.data)))
610
+ if self.op is Op.TERMS:
611
+ r = None
612
+ for term, coeff in self.data.items():
613
+ if r is None:
614
+ r = term.substitute(symbols_map) * coeff
615
+ else:
616
+ r += term.substitute(symbols_map) * coeff
617
+ if r is None:
618
+ ewarn('substitute: empty TERMS expression interpreted as'
619
+ ' int-literal 0')
620
+ return as_number(0)
621
+ return r
622
+ if self.op is Op.FACTORS:
623
+ r = None
624
+ for base, exponent in self.data.items():
625
+ if r is None:
626
+ r = base.substitute(symbols_map) ** exponent
627
+ else:
628
+ r *= base.substitute(symbols_map) ** exponent
629
+ if r is None:
630
+ ewarn('substitute: empty FACTORS expression interpreted'
631
+ ' as int-literal 1')
632
+ return as_number(1)
633
+ return r
634
+ if self.op is Op.APPLY:
635
+ target, args, kwargs = self.data
636
+ if isinstance(target, Expr):
637
+ target = target.substitute(symbols_map)
638
+ args = tuple(a.substitute(symbols_map) for a in args)
639
+ kwargs = dict((k, v.substitute(symbols_map))
640
+ for k, v in kwargs.items())
641
+ return normalize(Expr(self.op, (target, args, kwargs)))
642
+ if self.op is Op.INDEXING:
643
+ func = self.data[0]
644
+ if isinstance(func, Expr):
645
+ func = func.substitute(symbols_map)
646
+ args = tuple(a.substitute(symbols_map) for a in self.data[1:])
647
+ return normalize(Expr(self.op, (func,) + args))
648
+ if self.op is Op.TERNARY:
649
+ operands = tuple(a.substitute(symbols_map) for a in self.data)
650
+ return normalize(Expr(self.op, operands))
651
+ if self.op in (Op.REF, Op.DEREF):
652
+ return normalize(Expr(self.op, self.data.substitute(symbols_map)))
653
+ if self.op is Op.RELATIONAL:
654
+ rop, left, right = self.data
655
+ left = left.substitute(symbols_map)
656
+ right = right.substitute(symbols_map)
657
+ return normalize(Expr(self.op, (rop, left, right)))
658
+ raise NotImplementedError(f'substitute method for {self.op}: {self!r}')
659
+
660
+ def traverse(self, visit, *args, **kwargs):
661
+ """Traverse expression tree with visit function.
662
+
663
+ The visit function is applied to an expression with given args
664
+ and kwargs.
665
+
666
+ Traverse call returns an expression returned by visit when not
667
+ None, otherwise return a new normalized expression with
668
+ traverse-visit sub-expressions.
669
+ """
670
+ result = visit(self, *args, **kwargs)
671
+ if result is not None:
672
+ return result
673
+
674
+ if self.op in (Op.INTEGER, Op.REAL, Op.STRING, Op.SYMBOL):
675
+ return self
676
+ elif self.op in (Op.COMPLEX, Op.ARRAY, Op.CONCAT, Op.TERNARY):
677
+ return normalize(Expr(self.op, tuple(
678
+ item.traverse(visit, *args, **kwargs)
679
+ for item in self.data)))
680
+ elif self.op in (Op.TERMS, Op.FACTORS):
681
+ data = {}
682
+ for k, v in self.data.items():
683
+ k = k.traverse(visit, *args, **kwargs)
684
+ v = (v.traverse(visit, *args, **kwargs)
685
+ if isinstance(v, Expr) else v)
686
+ if k in data:
687
+ v = data[k] + v
688
+ data[k] = v
689
+ return normalize(Expr(self.op, data))
690
+ elif self.op is Op.APPLY:
691
+ obj = self.data[0]
692
+ func = (obj.traverse(visit, *args, **kwargs)
693
+ if isinstance(obj, Expr) else obj)
694
+ operands = tuple(operand.traverse(visit, *args, **kwargs)
695
+ for operand in self.data[1])
696
+ kwoperands = dict((k, v.traverse(visit, *args, **kwargs))
697
+ for k, v in self.data[2].items())
698
+ return normalize(Expr(self.op, (func, operands, kwoperands)))
699
+ elif self.op is Op.INDEXING:
700
+ obj = self.data[0]
701
+ obj = (obj.traverse(visit, *args, **kwargs)
702
+ if isinstance(obj, Expr) else obj)
703
+ indices = tuple(index.traverse(visit, *args, **kwargs)
704
+ for index in self.data[1:])
705
+ return normalize(Expr(self.op, (obj,) + indices))
706
+ elif self.op in (Op.REF, Op.DEREF):
707
+ return normalize(Expr(self.op,
708
+ self.data.traverse(visit, *args, **kwargs)))
709
+ elif self.op is Op.RELATIONAL:
710
+ rop, left, right = self.data
711
+ left = left.traverse(visit, *args, **kwargs)
712
+ right = right.traverse(visit, *args, **kwargs)
713
+ return normalize(Expr(self.op, (rop, left, right)))
714
+ raise NotImplementedError(f'traverse method for {self.op}')
715
+
716
+ def contains(self, other):
717
+ """Check if self contains other.
718
+ """
719
+ found = []
720
+
721
+ def visit(expr, found=found):
722
+ if found:
723
+ return expr
724
+ elif expr == other:
725
+ found.append(1)
726
+ return expr
727
+
728
+ self.traverse(visit)
729
+
730
+ return len(found) != 0
731
+
732
+ def symbols(self):
733
+ """Return a set of symbols contained in self.
734
+ """
735
+ found = set()
736
+
737
+ def visit(expr, found=found):
738
+ if expr.op is Op.SYMBOL:
739
+ found.add(expr)
740
+
741
+ self.traverse(visit)
742
+
743
+ return found
744
+
745
+ def polynomial_atoms(self):
746
+ """Return a set of expressions used as atoms in polynomial self.
747
+ """
748
+ found = set()
749
+
750
+ def visit(expr, found=found):
751
+ if expr.op is Op.FACTORS:
752
+ for b in expr.data:
753
+ b.traverse(visit)
754
+ return expr
755
+ if expr.op in (Op.TERMS, Op.COMPLEX):
756
+ return
757
+ if expr.op is Op.APPLY and isinstance(expr.data[0], ArithOp):
758
+ if expr.data[0] is ArithOp.POW:
759
+ expr.data[1][0].traverse(visit)
760
+ return expr
761
+ return
762
+ if expr.op in (Op.INTEGER, Op.REAL):
763
+ return expr
764
+
765
+ found.add(expr)
766
+
767
+ if expr.op in (Op.INDEXING, Op.APPLY):
768
+ return expr
769
+
770
+ self.traverse(visit)
771
+
772
+ return found
773
+
774
+ def linear_solve(self, symbol):
775
+ """Return a, b such that a * symbol + b == self.
776
+
777
+ If self is not linear with respect to symbol, raise RuntimeError.
778
+ """
779
+ b = self.substitute({symbol: as_number(0)})
780
+ ax = self - b
781
+ a = ax.substitute({symbol: as_number(1)})
782
+
783
+ zero, _ = as_numer_denom(a * symbol - ax)
784
+
785
+ if zero != as_number(0):
786
+ raise RuntimeError(f'not a {symbol}-linear equation:'
787
+ f' {a} * {symbol} + {b} == {self}')
788
+ return a, b
789
+
790
+
791
+ def normalize(obj):
792
+ """Normalize Expr and apply basic evaluation methods.
793
+ """
794
+ if not isinstance(obj, Expr):
795
+ return obj
796
+
797
+ if obj.op is Op.TERMS:
798
+ d = {}
799
+ for t, c in obj.data.items():
800
+ if c == 0:
801
+ continue
802
+ if t.op is Op.COMPLEX and c != 1:
803
+ t = t * c
804
+ c = 1
805
+ if t.op is Op.TERMS:
806
+ for t1, c1 in t.data.items():
807
+ _pairs_add(d, t1, c1 * c)
808
+ else:
809
+ _pairs_add(d, t, c)
810
+ if len(d) == 0:
811
+ # TODO: determine correct kind
812
+ return as_number(0)
813
+ elif len(d) == 1:
814
+ (t, c), = d.items()
815
+ if c == 1:
816
+ return t
817
+ return Expr(Op.TERMS, d)
818
+
819
+ if obj.op is Op.FACTORS:
820
+ coeff = 1
821
+ d = {}
822
+ for b, e in obj.data.items():
823
+ if e == 0:
824
+ continue
825
+ if b.op is Op.TERMS and isinstance(e, integer_types) and e > 1:
826
+ # expand integer powers of sums
827
+ b = b * (b ** (e - 1))
828
+ e = 1
829
+
830
+ if b.op in (Op.INTEGER, Op.REAL):
831
+ if e == 1:
832
+ coeff *= b.data[0]
833
+ elif e > 0:
834
+ coeff *= b.data[0] ** e
835
+ else:
836
+ _pairs_add(d, b, e)
837
+ elif b.op is Op.FACTORS:
838
+ if e > 0 and isinstance(e, integer_types):
839
+ for b1, e1 in b.data.items():
840
+ _pairs_add(d, b1, e1 * e)
841
+ else:
842
+ _pairs_add(d, b, e)
843
+ else:
844
+ _pairs_add(d, b, e)
845
+ if len(d) == 0 or coeff == 0:
846
+ # TODO: determine correct kind
847
+ assert isinstance(coeff, number_types)
848
+ return as_number(coeff)
849
+ elif len(d) == 1:
850
+ (b, e), = d.items()
851
+ if e == 1:
852
+ t = b
853
+ else:
854
+ t = Expr(Op.FACTORS, d)
855
+ if coeff == 1:
856
+ return t
857
+ return Expr(Op.TERMS, {t: coeff})
858
+ elif coeff == 1:
859
+ return Expr(Op.FACTORS, d)
860
+ else:
861
+ return Expr(Op.TERMS, {Expr(Op.FACTORS, d): coeff})
862
+
863
+ if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:
864
+ dividend, divisor = obj.data[1]
865
+ t1, c1 = as_term_coeff(dividend)
866
+ t2, c2 = as_term_coeff(divisor)
867
+ if isinstance(c1, integer_types) and isinstance(c2, integer_types):
868
+ g = gcd(c1, c2)
869
+ c1, c2 = c1//g, c2//g
870
+ else:
871
+ c1, c2 = c1/c2, 1
872
+
873
+ if t1.op is Op.APPLY and t1.data[0] is ArithOp.DIV:
874
+ numer = t1.data[1][0] * c1
875
+ denom = t1.data[1][1] * t2 * c2
876
+ return as_apply(ArithOp.DIV, numer, denom)
877
+
878
+ if t2.op is Op.APPLY and t2.data[0] is ArithOp.DIV:
879
+ numer = t2.data[1][1] * t1 * c1
880
+ denom = t2.data[1][0] * c2
881
+ return as_apply(ArithOp.DIV, numer, denom)
882
+
883
+ d = dict(as_factors(t1).data)
884
+ for b, e in as_factors(t2).data.items():
885
+ _pairs_add(d, b, -e)
886
+ numer, denom = {}, {}
887
+ for b, e in d.items():
888
+ if e > 0:
889
+ numer[b] = e
890
+ else:
891
+ denom[b] = -e
892
+ numer = normalize(Expr(Op.FACTORS, numer)) * c1
893
+ denom = normalize(Expr(Op.FACTORS, denom)) * c2
894
+
895
+ if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] == 1:
896
+ # TODO: denom kind not used
897
+ return numer
898
+ return as_apply(ArithOp.DIV, numer, denom)
899
+
900
+ if obj.op is Op.CONCAT:
901
+ lst = [obj.data[0]]
902
+ for s in obj.data[1:]:
903
+ last = lst[-1]
904
+ if (
905
+ last.op is Op.STRING
906
+ and s.op is Op.STRING
907
+ and last.data[0][0] in '"\''
908
+ and s.data[0][0] == last.data[0][-1]
909
+ ):
910
+ new_last = as_string(last.data[0][:-1] + s.data[0][1:],
911
+ max(last.data[1], s.data[1]))
912
+ lst[-1] = new_last
913
+ else:
914
+ lst.append(s)
915
+ if len(lst) == 1:
916
+ return lst[0]
917
+ return Expr(Op.CONCAT, tuple(lst))
918
+
919
+ if obj.op is Op.TERNARY:
920
+ cond, expr1, expr2 = map(normalize, obj.data)
921
+ if cond.op is Op.INTEGER:
922
+ return expr1 if cond.data[0] else expr2
923
+ return Expr(Op.TERNARY, (cond, expr1, expr2))
924
+
925
+ return obj
926
+
927
+
928
+ def as_expr(obj):
929
+ """Convert non-Expr objects to Expr objects.
930
+ """
931
+ if isinstance(obj, complex):
932
+ return as_complex(obj.real, obj.imag)
933
+ if isinstance(obj, number_types):
934
+ return as_number(obj)
935
+ if isinstance(obj, str):
936
+ # STRING expression holds string with boundary quotes, hence
937
+ # applying repr:
938
+ return as_string(repr(obj))
939
+ if isinstance(obj, tuple):
940
+ return tuple(map(as_expr, obj))
941
+ return obj
942
+
943
+
944
+ def as_symbol(obj):
945
+ """Return object as SYMBOL expression (variable or unparsed expression).
946
+ """
947
+ return Expr(Op.SYMBOL, obj)
948
+
949
+
950
+ def as_number(obj, kind=4):
951
+ """Return object as INTEGER or REAL constant.
952
+ """
953
+ if isinstance(obj, int):
954
+ return Expr(Op.INTEGER, (obj, kind))
955
+ if isinstance(obj, float):
956
+ return Expr(Op.REAL, (obj, kind))
957
+ if isinstance(obj, Expr):
958
+ if obj.op in (Op.INTEGER, Op.REAL):
959
+ return obj
960
+ raise OpError(f'cannot convert {obj} to INTEGER or REAL constant')
961
+
962
+
963
+ def as_integer(obj, kind=4):
964
+ """Return object as INTEGER constant.
965
+ """
966
+ if isinstance(obj, int):
967
+ return Expr(Op.INTEGER, (obj, kind))
968
+ if isinstance(obj, Expr):
969
+ if obj.op is Op.INTEGER:
970
+ return obj
971
+ raise OpError(f'cannot convert {obj} to INTEGER constant')
972
+
973
+
974
+ def as_real(obj, kind=4):
975
+ """Return object as REAL constant.
976
+ """
977
+ if isinstance(obj, int):
978
+ return Expr(Op.REAL, (float(obj), kind))
979
+ if isinstance(obj, float):
980
+ return Expr(Op.REAL, (obj, kind))
981
+ if isinstance(obj, Expr):
982
+ if obj.op is Op.REAL:
983
+ return obj
984
+ elif obj.op is Op.INTEGER:
985
+ return Expr(Op.REAL, (float(obj.data[0]), kind))
986
+ raise OpError(f'cannot convert {obj} to REAL constant')
987
+
988
+
989
+ def as_string(obj, kind=1):
990
+ """Return object as STRING expression (string literal constant).
991
+ """
992
+ return Expr(Op.STRING, (obj, kind))
993
+
994
+
995
+ def as_array(obj):
996
+ """Return object as ARRAY expression (array constant).
997
+ """
998
+ if isinstance(obj, Expr):
999
+ obj = obj,
1000
+ return Expr(Op.ARRAY, obj)
1001
+
1002
+
1003
+ def as_complex(real, imag=0):
1004
+ """Return object as COMPLEX expression (complex literal constant).
1005
+ """
1006
+ return Expr(Op.COMPLEX, (as_expr(real), as_expr(imag)))
1007
+
1008
+
1009
+ def as_apply(func, *args, **kwargs):
1010
+ """Return object as APPLY expression (function call, constructor, etc.)
1011
+ """
1012
+ return Expr(Op.APPLY,
1013
+ (func, tuple(map(as_expr, args)),
1014
+ dict((k, as_expr(v)) for k, v in kwargs.items())))
1015
+
1016
+
1017
+ def as_ternary(cond, expr1, expr2):
1018
+ """Return object as TERNARY expression (cond?expr1:expr2).
1019
+ """
1020
+ return Expr(Op.TERNARY, (cond, expr1, expr2))
1021
+
1022
+
1023
+ def as_ref(expr):
1024
+ """Return object as referencing expression.
1025
+ """
1026
+ return Expr(Op.REF, expr)
1027
+
1028
+
1029
+ def as_deref(expr):
1030
+ """Return object as dereferencing expression.
1031
+ """
1032
+ return Expr(Op.DEREF, expr)
1033
+
1034
+
1035
+ def as_eq(left, right):
1036
+ return Expr(Op.RELATIONAL, (RelOp.EQ, left, right))
1037
+
1038
+
1039
+ def as_ne(left, right):
1040
+ return Expr(Op.RELATIONAL, (RelOp.NE, left, right))
1041
+
1042
+
1043
+ def as_lt(left, right):
1044
+ return Expr(Op.RELATIONAL, (RelOp.LT, left, right))
1045
+
1046
+
1047
+ def as_le(left, right):
1048
+ return Expr(Op.RELATIONAL, (RelOp.LE, left, right))
1049
+
1050
+
1051
+ def as_gt(left, right):
1052
+ return Expr(Op.RELATIONAL, (RelOp.GT, left, right))
1053
+
1054
+
1055
+ def as_ge(left, right):
1056
+ return Expr(Op.RELATIONAL, (RelOp.GE, left, right))
1057
+
1058
+
1059
+ def as_terms(obj):
1060
+ """Return expression as TERMS expression.
1061
+ """
1062
+ if isinstance(obj, Expr):
1063
+ obj = normalize(obj)
1064
+ if obj.op is Op.TERMS:
1065
+ return obj
1066
+ if obj.op is Op.INTEGER:
1067
+ return Expr(Op.TERMS, {as_integer(1, obj.data[1]): obj.data[0]})
1068
+ if obj.op is Op.REAL:
1069
+ return Expr(Op.TERMS, {as_real(1, obj.data[1]): obj.data[0]})
1070
+ return Expr(Op.TERMS, {obj: 1})
1071
+ raise OpError(f'cannot convert {type(obj)} to terms Expr')
1072
+
1073
+
1074
+ def as_factors(obj):
1075
+ """Return expression as FACTORS expression.
1076
+ """
1077
+ if isinstance(obj, Expr):
1078
+ obj = normalize(obj)
1079
+ if obj.op is Op.FACTORS:
1080
+ return obj
1081
+ if obj.op is Op.TERMS:
1082
+ if len(obj.data) == 1:
1083
+ (term, coeff), = obj.data.items()
1084
+ if coeff == 1:
1085
+ return Expr(Op.FACTORS, {term: 1})
1086
+ return Expr(Op.FACTORS, {term: 1, Expr.number(coeff): 1})
1087
+ if ((obj.op is Op.APPLY
1088
+ and obj.data[0] is ArithOp.DIV
1089
+ and not obj.data[2])):
1090
+ return Expr(Op.FACTORS, {obj.data[1][0]: 1, obj.data[1][1]: -1})
1091
+ return Expr(Op.FACTORS, {obj: 1})
1092
+ raise OpError(f'cannot convert {type(obj)} to terms Expr')
1093
+
1094
+
1095
+ def as_term_coeff(obj):
1096
+ """Return expression as term-coefficient pair.
1097
+ """
1098
+ if isinstance(obj, Expr):
1099
+ obj = normalize(obj)
1100
+ if obj.op is Op.INTEGER:
1101
+ return as_integer(1, obj.data[1]), obj.data[0]
1102
+ if obj.op is Op.REAL:
1103
+ return as_real(1, obj.data[1]), obj.data[0]
1104
+ if obj.op is Op.TERMS:
1105
+ if len(obj.data) == 1:
1106
+ (term, coeff), = obj.data.items()
1107
+ return term, coeff
1108
+ # TODO: find common divisor of coefficients
1109
+ if obj.op is Op.APPLY and obj.data[0] is ArithOp.DIV:
1110
+ t, c = as_term_coeff(obj.data[1][0])
1111
+ return as_apply(ArithOp.DIV, t, obj.data[1][1]), c
1112
+ return obj, 1
1113
+ raise OpError(f'cannot convert {type(obj)} to term and coeff')
1114
+
1115
+
1116
+ def as_numer_denom(obj):
1117
+ """Return expression as numer-denom pair.
1118
+ """
1119
+ if isinstance(obj, Expr):
1120
+ obj = normalize(obj)
1121
+ if obj.op in (Op.INTEGER, Op.REAL, Op.COMPLEX, Op.SYMBOL,
1122
+ Op.INDEXING, Op.TERNARY):
1123
+ return obj, as_number(1)
1124
+ elif obj.op is Op.APPLY:
1125
+ if obj.data[0] is ArithOp.DIV and not obj.data[2]:
1126
+ numers, denoms = map(as_numer_denom, obj.data[1])
1127
+ return numers[0] * denoms[1], numers[1] * denoms[0]
1128
+ return obj, as_number(1)
1129
+ elif obj.op is Op.TERMS:
1130
+ numers, denoms = [], []
1131
+ for term, coeff in obj.data.items():
1132
+ n, d = as_numer_denom(term)
1133
+ n = n * coeff
1134
+ numers.append(n)
1135
+ denoms.append(d)
1136
+ numer, denom = as_number(0), as_number(1)
1137
+ for i in range(len(numers)):
1138
+ n = numers[i]
1139
+ for j in range(len(numers)):
1140
+ if i != j:
1141
+ n *= denoms[j]
1142
+ numer += n
1143
+ denom *= denoms[i]
1144
+ if denom.op in (Op.INTEGER, Op.REAL) and denom.data[0] < 0:
1145
+ numer, denom = -numer, -denom
1146
+ return numer, denom
1147
+ elif obj.op is Op.FACTORS:
1148
+ numer, denom = as_number(1), as_number(1)
1149
+ for b, e in obj.data.items():
1150
+ bnumer, bdenom = as_numer_denom(b)
1151
+ if e > 0:
1152
+ numer *= bnumer ** e
1153
+ denom *= bdenom ** e
1154
+ elif e < 0:
1155
+ numer *= bdenom ** (-e)
1156
+ denom *= bnumer ** (-e)
1157
+ return numer, denom
1158
+ raise OpError(f'cannot convert {type(obj)} to numer and denom')
1159
+
1160
+
1161
+ def _counter():
1162
+ # Used internally to generate unique dummy symbols
1163
+ counter = 0
1164
+ while True:
1165
+ counter += 1
1166
+ yield counter
1167
+
1168
+
1169
+ COUNTER = _counter()
1170
+
1171
+
1172
+ def eliminate_quotes(s):
1173
+ """Replace quoted substrings of input string.
1174
+
1175
+ Return a new string and a mapping of replacements.
1176
+ """
1177
+ d = {}
1178
+
1179
+ def repl(m):
1180
+ kind, value = m.groups()[:2]
1181
+ if kind:
1182
+ # remove trailing underscore
1183
+ kind = kind[:-1]
1184
+ p = {"'": "SINGLE", '"': "DOUBLE"}[value[0]]
1185
+ k = f'{kind}@__f2py_QUOTES_{p}_{COUNTER.__next__()}@'
1186
+ d[k] = value
1187
+ return k
1188
+
1189
+ new_s = re.sub(r'({kind}_|)({single_quoted}|{double_quoted})'.format(
1190
+ kind=r'\w[\w\d_]*',
1191
+ single_quoted=r"('([^'\\]|(\\.))*')",
1192
+ double_quoted=r'("([^"\\]|(\\.))*")'),
1193
+ repl, s)
1194
+
1195
+ assert '"' not in new_s
1196
+ assert "'" not in new_s
1197
+
1198
+ return new_s, d
1199
+
1200
+
1201
+ def insert_quotes(s, d):
1202
+ """Inverse of eliminate_quotes.
1203
+ """
1204
+ for k, v in d.items():
1205
+ kind = k[:k.find('@')]
1206
+ if kind:
1207
+ kind += '_'
1208
+ s = s.replace(k, kind + v)
1209
+ return s
1210
+
1211
+
1212
+ def replace_parenthesis(s):
1213
+ """Replace substrings of input that are enclosed in parenthesis.
1214
+
1215
+ Return a new string and a mapping of replacements.
1216
+ """
1217
+ # Find a parenthesis pair that appears first.
1218
+
1219
+ # Fortran deliminator are `(`, `)`, `[`, `]`, `(/', '/)`, `/`.
1220
+ # We don't handle `/` deliminator because it is not a part of an
1221
+ # expression.
1222
+ left, right = None, None
1223
+ mn_i = len(s)
1224
+ for left_, right_ in (('(/', '/)'),
1225
+ '()',
1226
+ '{}', # to support C literal structs
1227
+ '[]'):
1228
+ i = s.find(left_)
1229
+ if i == -1:
1230
+ continue
1231
+ if i < mn_i:
1232
+ mn_i = i
1233
+ left, right = left_, right_
1234
+
1235
+ if left is None:
1236
+ return s, {}
1237
+
1238
+ i = mn_i
1239
+ j = s.find(right, i)
1240
+
1241
+ while s.count(left, i + 1, j) != s.count(right, i + 1, j):
1242
+ j = s.find(right, j + 1)
1243
+ if j == -1:
1244
+ raise ValueError(f'Mismatch of {left+right} parenthesis in {s!r}')
1245
+
1246
+ p = {'(': 'ROUND', '[': 'SQUARE', '{': 'CURLY', '(/': 'ROUNDDIV'}[left]
1247
+
1248
+ k = f'@__f2py_PARENTHESIS_{p}_{COUNTER.__next__()}@'
1249
+ v = s[i+len(left):j]
1250
+ r, d = replace_parenthesis(s[j+len(right):])
1251
+ d[k] = v
1252
+ return s[:i] + k + r, d
1253
+
1254
+
1255
+ def _get_parenthesis_kind(s):
1256
+ assert s.startswith('@__f2py_PARENTHESIS_'), s
1257
+ return s.split('_')[4]
1258
+
1259
+
1260
+ def unreplace_parenthesis(s, d):
1261
+ """Inverse of replace_parenthesis.
1262
+ """
1263
+ for k, v in d.items():
1264
+ p = _get_parenthesis_kind(k)
1265
+ left = dict(ROUND='(', SQUARE='[', CURLY='{', ROUNDDIV='(/')[p]
1266
+ right = dict(ROUND=')', SQUARE=']', CURLY='}', ROUNDDIV='/)')[p]
1267
+ s = s.replace(k, left + v + right)
1268
+ return s
1269
+
1270
+
1271
+ def fromstring(s, language=Language.C):
1272
+ """Create an expression from a string.
1273
+
1274
+ This is a "lazy" parser, that is, only arithmetic operations are
1275
+ resolved, non-arithmetic operations are treated as symbols.
1276
+ """
1277
+ r = _FromStringWorker(language=language).parse(s)
1278
+ if isinstance(r, Expr):
1279
+ return r
1280
+ raise ValueError(f'failed to parse `{s}` to Expr instance: got `{r}`')
1281
+
1282
+
1283
+ class _Pair:
1284
+ # Internal class to represent a pair of expressions
1285
+
1286
+ def __init__(self, left, right):
1287
+ self.left = left
1288
+ self.right = right
1289
+
1290
+ def substitute(self, symbols_map):
1291
+ left, right = self.left, self.right
1292
+ if isinstance(left, Expr):
1293
+ left = left.substitute(symbols_map)
1294
+ if isinstance(right, Expr):
1295
+ right = right.substitute(symbols_map)
1296
+ return _Pair(left, right)
1297
+
1298
+ def __repr__(self):
1299
+ return f'{type(self).__name__}({self.left}, {self.right})'
1300
+
1301
+
1302
+ class _FromStringWorker:
1303
+
1304
+ def __init__(self, language=Language.C):
1305
+ self.original = None
1306
+ self.quotes_map = None
1307
+ self.language = language
1308
+
1309
+ def finalize_string(self, s):
1310
+ return insert_quotes(s, self.quotes_map)
1311
+
1312
+ def parse(self, inp):
1313
+ self.original = inp
1314
+ unquoted, self.quotes_map = eliminate_quotes(inp)
1315
+ return self.process(unquoted)
1316
+
1317
+ def process(self, s, context='expr'):
1318
+ """Parse string within the given context.
1319
+
1320
+ The context may define the result in case of ambiguous
1321
+ expressions. For instance, consider expressions `f(x, y)` and
1322
+ `(x, y) + (a, b)` where `f` is a function and pair `(x, y)`
1323
+ denotes complex number. Specifying context as "args" or
1324
+ "expr", the subexpression `(x, y)` will be parse to an
1325
+ argument list or to a complex number, respectively.
1326
+ """
1327
+ if isinstance(s, (list, tuple)):
1328
+ return type(s)(self.process(s_, context) for s_ in s)
1329
+
1330
+ assert isinstance(s, str), (type(s), s)
1331
+
1332
+ # replace subexpressions in parenthesis with f2py @-names
1333
+ r, raw_symbols_map = replace_parenthesis(s)
1334
+ r = r.strip()
1335
+
1336
+ def restore(r):
1337
+ # restores subexpressions marked with f2py @-names
1338
+ if isinstance(r, (list, tuple)):
1339
+ return type(r)(map(restore, r))
1340
+ return unreplace_parenthesis(r, raw_symbols_map)
1341
+
1342
+ # comma-separated tuple
1343
+ if ',' in r:
1344
+ operands = restore(r.split(','))
1345
+ if context == 'args':
1346
+ return tuple(self.process(operands))
1347
+ if context == 'expr':
1348
+ if len(operands) == 2:
1349
+ # complex number literal
1350
+ return as_complex(*self.process(operands))
1351
+ raise NotImplementedError(
1352
+ f'parsing comma-separated list (context={context}): {r}')
1353
+
1354
+ # ternary operation
1355
+ m = re.match(r'\A([^?]+)[?]([^:]+)[:](.+)\Z', r)
1356
+ if m:
1357
+ assert context == 'expr', context
1358
+ oper, expr1, expr2 = restore(m.groups())
1359
+ oper = self.process(oper)
1360
+ expr1 = self.process(expr1)
1361
+ expr2 = self.process(expr2)
1362
+ return as_ternary(oper, expr1, expr2)
1363
+
1364
+ # relational expression
1365
+ if self.language is Language.Fortran:
1366
+ m = re.match(
1367
+ r'\A(.+)\s*[.](eq|ne|lt|le|gt|ge)[.]\s*(.+)\Z', r, re.I)
1368
+ else:
1369
+ m = re.match(
1370
+ r'\A(.+)\s*([=][=]|[!][=]|[<][=]|[<]|[>][=]|[>])\s*(.+)\Z', r)
1371
+ if m:
1372
+ left, rop, right = m.groups()
1373
+ if self.language is Language.Fortran:
1374
+ rop = '.' + rop + '.'
1375
+ left, right = self.process(restore((left, right)))
1376
+ rop = RelOp.fromstring(rop, language=self.language)
1377
+ return Expr(Op.RELATIONAL, (rop, left, right))
1378
+
1379
+ # keyword argument
1380
+ m = re.match(r'\A(\w[\w\d_]*)\s*[=](.*)\Z', r)
1381
+ if m:
1382
+ keyname, value = m.groups()
1383
+ value = restore(value)
1384
+ return _Pair(keyname, self.process(value))
1385
+
1386
+ # addition/subtraction operations
1387
+ operands = re.split(r'((?<!\d[edED])[+-])', r)
1388
+ if len(operands) > 1:
1389
+ result = self.process(restore(operands[0] or '0'))
1390
+ for op, operand in zip(operands[1::2], operands[2::2]):
1391
+ operand = self.process(restore(operand))
1392
+ op = op.strip()
1393
+ if op == '+':
1394
+ result += operand
1395
+ else:
1396
+ assert op == '-'
1397
+ result -= operand
1398
+ return result
1399
+
1400
+ # string concatenate operation
1401
+ if self.language is Language.Fortran and '//' in r:
1402
+ operands = restore(r.split('//'))
1403
+ return Expr(Op.CONCAT,
1404
+ tuple(self.process(operands)))
1405
+
1406
+ # multiplication/division operations
1407
+ operands = re.split(r'(?<=[@\w\d_])\s*([*]|/)',
1408
+ (r if self.language is Language.C
1409
+ else r.replace('**', '@__f2py_DOUBLE_STAR@')))
1410
+ if len(operands) > 1:
1411
+ operands = restore(operands)
1412
+ if self.language is not Language.C:
1413
+ operands = [operand.replace('@__f2py_DOUBLE_STAR@', '**')
1414
+ for operand in operands]
1415
+ # Expression is an arithmetic product
1416
+ result = self.process(operands[0])
1417
+ for op, operand in zip(operands[1::2], operands[2::2]):
1418
+ operand = self.process(operand)
1419
+ op = op.strip()
1420
+ if op == '*':
1421
+ result *= operand
1422
+ else:
1423
+ assert op == '/'
1424
+ result /= operand
1425
+ return result
1426
+
1427
+ # referencing/dereferencing
1428
+ if r.startswith('*') or r.startswith('&'):
1429
+ op = {'*': Op.DEREF, '&': Op.REF}[r[0]]
1430
+ operand = self.process(restore(r[1:]))
1431
+ return Expr(op, operand)
1432
+
1433
+ # exponentiation operations
1434
+ if self.language is not Language.C and '**' in r:
1435
+ operands = list(reversed(restore(r.split('**'))))
1436
+ result = self.process(operands[0])
1437
+ for operand in operands[1:]:
1438
+ operand = self.process(operand)
1439
+ result = operand ** result
1440
+ return result
1441
+
1442
+ # int-literal-constant
1443
+ m = re.match(r'\A({digit_string})({kind}|)\Z'.format(
1444
+ digit_string=r'\d+',
1445
+ kind=r'_(\d+|\w[\w\d_]*)'), r)
1446
+ if m:
1447
+ value, _, kind = m.groups()
1448
+ if kind and kind.isdigit():
1449
+ kind = int(kind)
1450
+ return as_integer(int(value), kind or 4)
1451
+
1452
+ # real-literal-constant
1453
+ m = re.match(r'\A({significant}({exponent}|)|\d+{exponent})({kind}|)\Z'
1454
+ .format(
1455
+ significant=r'[.]\d+|\d+[.]\d*',
1456
+ exponent=r'[edED][+-]?\d+',
1457
+ kind=r'_(\d+|\w[\w\d_]*)'), r)
1458
+ if m:
1459
+ value, _, _, kind = m.groups()
1460
+ if kind and kind.isdigit():
1461
+ kind = int(kind)
1462
+ value = value.lower()
1463
+ if 'd' in value:
1464
+ return as_real(float(value.replace('d', 'e')), kind or 8)
1465
+ return as_real(float(value), kind or 4)
1466
+
1467
+ # string-literal-constant with kind parameter specification
1468
+ if r in self.quotes_map:
1469
+ kind = r[:r.find('@')]
1470
+ return as_string(self.quotes_map[r], kind or 1)
1471
+
1472
+ # array constructor or literal complex constant or
1473
+ # parenthesized expression
1474
+ if r in raw_symbols_map:
1475
+ paren = _get_parenthesis_kind(r)
1476
+ items = self.process(restore(raw_symbols_map[r]),
1477
+ 'expr' if paren == 'ROUND' else 'args')
1478
+ if paren == 'ROUND':
1479
+ if isinstance(items, Expr):
1480
+ return items
1481
+ if paren in ['ROUNDDIV', 'SQUARE']:
1482
+ # Expression is a array constructor
1483
+ if isinstance(items, Expr):
1484
+ items = (items,)
1485
+ return as_array(items)
1486
+
1487
+ # function call/indexing
1488
+ m = re.match(r'\A(.+)\s*(@__f2py_PARENTHESIS_(ROUND|SQUARE)_\d+@)\Z',
1489
+ r)
1490
+ if m:
1491
+ target, args, paren = m.groups()
1492
+ target = self.process(restore(target))
1493
+ args = self.process(restore(args)[1:-1], 'args')
1494
+ if not isinstance(args, tuple):
1495
+ args = args,
1496
+ if paren == 'ROUND':
1497
+ kwargs = dict((a.left, a.right) for a in args
1498
+ if isinstance(a, _Pair))
1499
+ args = tuple(a for a in args if not isinstance(a, _Pair))
1500
+ # Warning: this could also be Fortran indexing operation..
1501
+ return as_apply(target, *args, **kwargs)
1502
+ else:
1503
+ # Expression is a C/Python indexing operation
1504
+ # (e.g. used in .pyf files)
1505
+ assert paren == 'SQUARE'
1506
+ return target[args]
1507
+
1508
+ # Fortran standard conforming identifier
1509
+ m = re.match(r'\A\w[\w\d_]*\Z', r)
1510
+ if m:
1511
+ return as_symbol(r)
1512
+
1513
+ # fall-back to symbol
1514
+ r = self.finalize_string(restore(r))
1515
+ ewarn(
1516
+ f'fromstring: treating {r!r} as symbol (original={self.original})')
1517
+ return as_symbol(r)
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_callback.cpython-310.pyc ADDED
Binary file (8.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_compile_function.cpython-310.pyc ADDED
Binary file (2.42 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_docs.cpython-310.pyc ADDED
Binary file (2.01 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_mixed.cpython-310.pyc ADDED
Binary file (1.28 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_regression.cpython-310.pyc ADDED
Binary file (2.88 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_return_logical.cpython-310.pyc ADDED
Binary file (2.43 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_semicolon_split.cpython-310.pyc ADDED
Binary file (1.98 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/__pycache__/test_size.cpython-310.pyc ADDED
Binary file (1.69 kB). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/abstract_interface/foo.f90 ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module ops_module
2
+
3
+ abstract interface
4
+ subroutine op(x, y, z)
5
+ integer, intent(in) :: x, y
6
+ integer, intent(out) :: z
7
+ end subroutine
8
+ end interface
9
+
10
+ contains
11
+
12
+ subroutine foo(x, y, r1, r2)
13
+ integer, intent(in) :: x, y
14
+ integer, intent(out) :: r1, r2
15
+ procedure (op) add1, add2
16
+ procedure (op), pointer::p
17
+ p=>add1
18
+ call p(x, y, r1)
19
+ p=>add2
20
+ call p(x, y, r2)
21
+ end subroutine
22
+ end module
23
+
24
+ subroutine add1(x, y, z)
25
+ integer, intent(in) :: x, y
26
+ integer, intent(out) :: z
27
+ z = x + y
28
+ end subroutine
29
+
30
+ subroutine add2(x, y, z)
31
+ integer, intent(in) :: x, y
32
+ integer, intent(out) :: z
33
+ z = x + 2 * y
34
+ end subroutine
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ module test
2
+ abstract interface
3
+ subroutine foo()
4
+ end subroutine
5
+ end interface
6
+ end module test
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * This file was auto-generated with f2py (version:2_1330) and hand edited by
3
+ * Pearu for testing purposes. Do not edit this file unless you know what you
4
+ * are doing!!!
5
+ */
6
+
7
+ #ifdef __cplusplus
8
+ extern "C" {
9
+ #endif
10
+
11
+ /*********************** See f2py2e/cfuncs.py: includes ***********************/
12
+
13
+ #define PY_SSIZE_T_CLEAN
14
+ #include <Python.h>
15
+ #include "fortranobject.h"
16
+ #include <math.h>
17
+
18
+ static PyObject *wrap_error;
19
+ static PyObject *wrap_module;
20
+
21
+ /************************************ call ************************************/
22
+ static char doc_f2py_rout_wrap_call[] = "\
23
+ Function signature:\n\
24
+ arr = call(type_num,dims,intent,obj)\n\
25
+ Required arguments:\n"
26
+ " type_num : input int\n"
27
+ " dims : input int-sequence\n"
28
+ " intent : input int\n"
29
+ " obj : input python object\n"
30
+ "Return objects:\n"
31
+ " arr : array";
32
+ static PyObject *f2py_rout_wrap_call(PyObject *capi_self,
33
+ PyObject *capi_args) {
34
+ PyObject * volatile capi_buildvalue = NULL;
35
+ int type_num = 0;
36
+ int elsize = 0;
37
+ npy_intp *dims = NULL;
38
+ PyObject *dims_capi = Py_None;
39
+ int rank = 0;
40
+ int intent = 0;
41
+ PyArrayObject *capi_arr_tmp = NULL;
42
+ PyObject *arr_capi = Py_None;
43
+ int i;
44
+
45
+ if (!PyArg_ParseTuple(capi_args,"iiOiO|:wrap.call",\
46
+ &type_num,&elsize,&dims_capi,&intent,&arr_capi))
47
+ return NULL;
48
+ rank = PySequence_Length(dims_capi);
49
+ dims = malloc(rank*sizeof(npy_intp));
50
+ for (i=0;i<rank;++i) {
51
+ PyObject *tmp;
52
+ tmp = PySequence_GetItem(dims_capi, i);
53
+ if (tmp == NULL) {
54
+ goto fail;
55
+ }
56
+ dims[i] = (npy_intp)PyLong_AsLong(tmp);
57
+ Py_DECREF(tmp);
58
+ if (dims[i] == -1 && PyErr_Occurred()) {
59
+ goto fail;
60
+ }
61
+ }
62
+ capi_arr_tmp = ndarray_from_pyobj(type_num,elsize,dims,rank,intent|F2PY_INTENT_OUT,arr_capi,"wrap.call failed");
63
+ if (capi_arr_tmp == NULL) {
64
+ free(dims);
65
+ return NULL;
66
+ }
67
+ capi_buildvalue = Py_BuildValue("N",capi_arr_tmp);
68
+ free(dims);
69
+ return capi_buildvalue;
70
+
71
+ fail:
72
+ free(dims);
73
+ return NULL;
74
+ }
75
+
76
+ static char doc_f2py_rout_wrap_attrs[] = "\
77
+ Function signature:\n\
78
+ arr = array_attrs(arr)\n\
79
+ Required arguments:\n"
80
+ " arr : input array object\n"
81
+ "Return objects:\n"
82
+ " data : data address in hex\n"
83
+ " nd : int\n"
84
+ " dimensions : tuple\n"
85
+ " strides : tuple\n"
86
+ " base : python object\n"
87
+ " (kind,type,type_num,elsize,alignment) : 4-tuple\n"
88
+ " flags : int\n"
89
+ " itemsize : int\n"
90
+ ;
91
+ static PyObject *f2py_rout_wrap_attrs(PyObject *capi_self,
92
+ PyObject *capi_args) {
93
+ PyObject *arr_capi = Py_None;
94
+ PyArrayObject *arr = NULL;
95
+ PyObject *dimensions = NULL;
96
+ PyObject *strides = NULL;
97
+ char s[100];
98
+ int i;
99
+ memset(s,0,100);
100
+ if (!PyArg_ParseTuple(capi_args,"O!|:wrap.attrs",
101
+ &PyArray_Type,&arr_capi))
102
+ return NULL;
103
+ arr = (PyArrayObject *)arr_capi;
104
+ sprintf(s,"%p",PyArray_DATA(arr));
105
+ dimensions = PyTuple_New(PyArray_NDIM(arr));
106
+ strides = PyTuple_New(PyArray_NDIM(arr));
107
+ for (i=0;i<PyArray_NDIM(arr);++i) {
108
+ PyTuple_SetItem(dimensions,i,PyLong_FromLong(PyArray_DIM(arr,i)));
109
+ PyTuple_SetItem(strides,i,PyLong_FromLong(PyArray_STRIDE(arr,i)));
110
+ }
111
+ return Py_BuildValue("siNNO(cciii)ii",s,PyArray_NDIM(arr),
112
+ dimensions,strides,
113
+ (PyArray_BASE(arr)==NULL?Py_None:PyArray_BASE(arr)),
114
+ PyArray_DESCR(arr)->kind,
115
+ PyArray_DESCR(arr)->type,
116
+ PyArray_TYPE(arr),
117
+ PyArray_ITEMSIZE(arr),
118
+ PyArray_DESCR(arr)->alignment,
119
+ PyArray_FLAGS(arr),
120
+ PyArray_ITEMSIZE(arr));
121
+ }
122
+
123
+ static PyMethodDef f2py_module_methods[] = {
124
+
125
+ {"call",f2py_rout_wrap_call,METH_VARARGS,doc_f2py_rout_wrap_call},
126
+ {"array_attrs",f2py_rout_wrap_attrs,METH_VARARGS,doc_f2py_rout_wrap_attrs},
127
+ {NULL,NULL}
128
+ };
129
+
130
+ static struct PyModuleDef moduledef = {
131
+ PyModuleDef_HEAD_INIT,
132
+ "test_array_from_pyobj_ext",
133
+ NULL,
134
+ -1,
135
+ f2py_module_methods,
136
+ NULL,
137
+ NULL,
138
+ NULL,
139
+ NULL
140
+ };
141
+
142
+ PyMODINIT_FUNC PyInit_test_array_from_pyobj_ext(void) {
143
+ PyObject *m,*d, *s;
144
+ m = wrap_module = PyModule_Create(&moduledef);
145
+ Py_SET_TYPE(&PyFortran_Type, &PyType_Type);
146
+ import_array();
147
+ if (PyErr_Occurred())
148
+ Py_FatalError("can't initialize module wrap (failed to import numpy)");
149
+ d = PyModule_GetDict(m);
150
+ s = PyUnicode_FromString("This module 'wrap' is auto-generated with f2py (version:2_1330).\nFunctions:\n"
151
+ " arr = call(type_num,dims,intent,obj)\n"
152
+ ".");
153
+ PyDict_SetItemString(d, "__doc__", s);
154
+ wrap_error = PyErr_NewException ("wrap.error", NULL, NULL);
155
+ Py_DECREF(s);
156
+
157
+ #define ADDCONST(NAME, CONST) \
158
+ s = PyLong_FromLong(CONST); \
159
+ PyDict_SetItemString(d, NAME, s); \
160
+ Py_DECREF(s)
161
+
162
+ ADDCONST("F2PY_INTENT_IN", F2PY_INTENT_IN);
163
+ ADDCONST("F2PY_INTENT_INOUT", F2PY_INTENT_INOUT);
164
+ ADDCONST("F2PY_INTENT_OUT", F2PY_INTENT_OUT);
165
+ ADDCONST("F2PY_INTENT_HIDE", F2PY_INTENT_HIDE);
166
+ ADDCONST("F2PY_INTENT_CACHE", F2PY_INTENT_CACHE);
167
+ ADDCONST("F2PY_INTENT_COPY", F2PY_INTENT_COPY);
168
+ ADDCONST("F2PY_INTENT_C", F2PY_INTENT_C);
169
+ ADDCONST("F2PY_OPTIONAL", F2PY_OPTIONAL);
170
+ ADDCONST("F2PY_INTENT_INPLACE", F2PY_INTENT_INPLACE);
171
+ ADDCONST("NPY_BOOL", NPY_BOOL);
172
+ ADDCONST("NPY_BYTE", NPY_BYTE);
173
+ ADDCONST("NPY_UBYTE", NPY_UBYTE);
174
+ ADDCONST("NPY_SHORT", NPY_SHORT);
175
+ ADDCONST("NPY_USHORT", NPY_USHORT);
176
+ ADDCONST("NPY_INT", NPY_INT);
177
+ ADDCONST("NPY_UINT", NPY_UINT);
178
+ ADDCONST("NPY_INTP", NPY_INTP);
179
+ ADDCONST("NPY_UINTP", NPY_UINTP);
180
+ ADDCONST("NPY_LONG", NPY_LONG);
181
+ ADDCONST("NPY_ULONG", NPY_ULONG);
182
+ ADDCONST("NPY_LONGLONG", NPY_LONGLONG);
183
+ ADDCONST("NPY_ULONGLONG", NPY_ULONGLONG);
184
+ ADDCONST("NPY_FLOAT", NPY_FLOAT);
185
+ ADDCONST("NPY_DOUBLE", NPY_DOUBLE);
186
+ ADDCONST("NPY_LONGDOUBLE", NPY_LONGDOUBLE);
187
+ ADDCONST("NPY_CFLOAT", NPY_CFLOAT);
188
+ ADDCONST("NPY_CDOUBLE", NPY_CDOUBLE);
189
+ ADDCONST("NPY_CLONGDOUBLE", NPY_CLONGDOUBLE);
190
+ ADDCONST("NPY_OBJECT", NPY_OBJECT);
191
+ ADDCONST("NPY_STRING", NPY_STRING);
192
+ ADDCONST("NPY_UNICODE", NPY_UNICODE);
193
+ ADDCONST("NPY_VOID", NPY_VOID);
194
+ ADDCONST("NPY_NTYPES", NPY_NTYPES);
195
+ ADDCONST("NPY_NOTYPE", NPY_NOTYPE);
196
+ ADDCONST("NPY_USERDEF", NPY_USERDEF);
197
+
198
+ ADDCONST("CONTIGUOUS", NPY_ARRAY_C_CONTIGUOUS);
199
+ ADDCONST("FORTRAN", NPY_ARRAY_F_CONTIGUOUS);
200
+ ADDCONST("OWNDATA", NPY_ARRAY_OWNDATA);
201
+ ADDCONST("FORCECAST", NPY_ARRAY_FORCECAST);
202
+ ADDCONST("ENSURECOPY", NPY_ARRAY_ENSURECOPY);
203
+ ADDCONST("ENSUREARRAY", NPY_ARRAY_ENSUREARRAY);
204
+ ADDCONST("ALIGNED", NPY_ARRAY_ALIGNED);
205
+ ADDCONST("WRITEABLE", NPY_ARRAY_WRITEABLE);
206
+ ADDCONST("WRITEBACKIFCOPY", NPY_ARRAY_WRITEBACKIFCOPY);
207
+
208
+ ADDCONST("BEHAVED", NPY_ARRAY_BEHAVED);
209
+ ADDCONST("BEHAVED_NS", NPY_ARRAY_BEHAVED_NS);
210
+ ADDCONST("CARRAY", NPY_ARRAY_CARRAY);
211
+ ADDCONST("FARRAY", NPY_ARRAY_FARRAY);
212
+ ADDCONST("CARRAY_RO", NPY_ARRAY_CARRAY_RO);
213
+ ADDCONST("FARRAY_RO", NPY_ARRAY_FARRAY_RO);
214
+ ADDCONST("DEFAULT", NPY_ARRAY_DEFAULT);
215
+ ADDCONST("UPDATE_ALL", NPY_ARRAY_UPDATE_ALL);
216
+
217
+ #undef ADDCONST(
218
+
219
+ if (PyErr_Occurred())
220
+ Py_FatalError("can't initialize module wrap");
221
+
222
+ #ifdef F2PY_REPORT_ATEXIT
223
+ on_exit(f2py_report_on_exit,(void*)"array_from_pyobj.wrap.call");
224
+ #endif
225
+
226
+ return m;
227
+ }
228
+ #ifdef __cplusplus
229
+ }
230
+ #endif
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap ADDED
@@ -0,0 +1 @@
 
 
1
+ dict(real=dict(rk="double"))
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/foo_free.f90 ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ subroutine sum(x, res)
3
+ implicit none
4
+ real, intent(in) :: x(:)
5
+ real, intent(out) :: res
6
+
7
+ integer :: i
8
+
9
+ !print *, "sum: size(x) = ", size(x)
10
+
11
+ res = 0.0
12
+
13
+ do i = 1, size(x)
14
+ res = res + x(i)
15
+ enddo
16
+
17
+ end subroutine sum
18
+
19
+ function fsum(x) result (res)
20
+ implicit none
21
+ real, intent(in) :: x(:)
22
+ real :: res
23
+
24
+ integer :: i
25
+
26
+ !print *, "fsum: size(x) = ", size(x)
27
+
28
+ res = 0.0
29
+
30
+ do i = 1, size(x)
31
+ res = res + x(i)
32
+ enddo
33
+
34
+ end function fsum
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/foo_mod.f90 ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ module mod
3
+
4
+ contains
5
+
6
+ subroutine sum(x, res)
7
+ implicit none
8
+ real, intent(in) :: x(:)
9
+ real, intent(out) :: res
10
+
11
+ integer :: i
12
+
13
+ !print *, "sum: size(x) = ", size(x)
14
+
15
+ res = 0.0
16
+
17
+ do i = 1, size(x)
18
+ res = res + x(i)
19
+ enddo
20
+
21
+ end subroutine sum
22
+
23
+ function fsum(x) result (res)
24
+ implicit none
25
+ real, intent(in) :: x(:)
26
+ real :: res
27
+
28
+ integer :: i
29
+
30
+ !print *, "fsum: size(x) = ", size(x)
31
+
32
+ res = 0.0
33
+
34
+ do i = 1, size(x)
35
+ res = res + x(i)
36
+ enddo
37
+
38
+ end function fsum
39
+
40
+
41
+ end module mod
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/foo_use.f90 ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ subroutine sum_with_use(x, res)
2
+ use precision
3
+
4
+ implicit none
5
+
6
+ real(kind=rk), intent(in) :: x(:)
7
+ real(kind=rk), intent(out) :: res
8
+
9
+ integer :: i
10
+
11
+ !print *, "size(x) = ", size(x)
12
+
13
+ res = 0.0
14
+
15
+ do i = 1, size(x)
16
+ res = res + x(i)
17
+ enddo
18
+
19
+ end subroutine
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/assumed_shape/precision.f90 ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ module precision
2
+ integer, parameter :: rk = selected_real_kind(8)
3
+ integer, parameter :: ik = selected_real_kind(4)
4
+ end module
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/block_docstring/foo.f ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ SUBROUTINE FOO()
2
+ INTEGER BAR(2, 3)
3
+
4
+ COMMON /BLOCK/ BAR
5
+ RETURN
6
+ END
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/foo.f ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ subroutine t(fun,a)
2
+ integer a
3
+ cf2py intent(out) a
4
+ external fun
5
+ call fun(a)
6
+ end
7
+
8
+ subroutine func(a)
9
+ cf2py intent(in,out) a
10
+ integer a
11
+ a = a + 11
12
+ end
13
+
14
+ subroutine func0(a)
15
+ cf2py intent(out) a
16
+ integer a
17
+ a = 11
18
+ end
19
+
20
+ subroutine t2(a)
21
+ cf2py intent(callback) fun
22
+ integer a
23
+ cf2py intent(out) a
24
+ external fun
25
+ call fun(a)
26
+ end
27
+
28
+ subroutine string_callback(callback, a)
29
+ external callback
30
+ double precision callback
31
+ double precision a
32
+ character*1 r
33
+ cf2py intent(out) a
34
+ r = 'r'
35
+ a = callback(r)
36
+ end
37
+
38
+ subroutine string_callback_array(callback, cu, lencu, a)
39
+ external callback
40
+ integer callback
41
+ integer lencu
42
+ character*8 cu(lencu)
43
+ integer a
44
+ cf2py intent(out) a
45
+
46
+ a = callback(cu, lencu)
47
+ end
48
+
49
+ subroutine hidden_callback(a, r)
50
+ external global_f
51
+ cf2py intent(callback, hide) global_f
52
+ integer a, r, global_f
53
+ cf2py intent(out) r
54
+ r = global_f(a)
55
+ end
56
+
57
+ subroutine hidden_callback2(a, r)
58
+ external global_f
59
+ integer a, r, global_f
60
+ cf2py intent(out) r
61
+ r = global_f(a)
62
+ end
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh17797.f90 ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ function gh17797(f, y) result(r)
2
+ external f
3
+ integer(8) :: r, f
4
+ integer(8), dimension(:) :: y
5
+ r = f(0)
6
+ r = r + sum(y)
7
+ end function gh17797
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh18335.f90 ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ! When gh18335_workaround is defined as an extension,
2
+ ! the issue cannot be reproduced.
3
+ !subroutine gh18335_workaround(f, y)
4
+ ! implicit none
5
+ ! external f
6
+ ! integer(kind=1) :: y(1)
7
+ ! call f(y)
8
+ !end subroutine gh18335_workaround
9
+
10
+ function gh18335(f) result (r)
11
+ implicit none
12
+ external f
13
+ integer(kind=1) :: y(1), r
14
+ y(1) = 123
15
+ call f(y)
16
+ r = y(1)
17
+ end function gh18335
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh25211.f ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ SUBROUTINE FOO(FUN,R)
2
+ EXTERNAL FUN
3
+ INTEGER I
4
+ REAL*8 R, FUN
5
+ Cf2py intent(out) r
6
+ R = 0D0
7
+ DO I=-5,5
8
+ R = R + FUN(I)
9
+ ENDDO
10
+ END
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/callback/gh25211.pyf ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ python module __user__routines
2
+ interface
3
+ function fun(i) result (r)
4
+ integer :: i
5
+ real*8 :: r
6
+ end function fun
7
+ end interface
8
+ end python module __user__routines
9
+
10
+ python module callback2
11
+ interface
12
+ subroutine foo(f,r)
13
+ use __user__routines, f=>fun
14
+ external f
15
+ real*8 intent(out) :: r
16
+ end subroutine foo
17
+ end interface
18
+ end python module callback2
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/cli/gh_22819.pyf ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ python module test_22819
2
+ interface
3
+ subroutine hello()
4
+ end subroutine hello
5
+ end interface
6
+ end python module test_22819
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/cli/hi77.f ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ SUBROUTINE HI
2
+ PRINT*, "HELLO WORLD"
3
+ END SUBROUTINE
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/cli/hiworld.f90 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ function hi()
2
+ print*, "Hello World"
3
+ end function
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/common/block.f ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SUBROUTINE INITCB
2
+ DOUBLE PRECISION LONG
3
+ CHARACTER STRING
4
+ INTEGER OK
5
+
6
+ COMMON /BLOCK/ LONG, STRING, OK
7
+ LONG = 1.0
8
+ STRING = '2'
9
+ OK = 3
10
+ RETURN
11
+ END
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/common/gh19161.f90 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ module typedefmod
2
+ use iso_fortran_env, only: real32
3
+ end module typedefmod
4
+
5
+ module data
6
+ use typedefmod, only: real32
7
+ implicit none
8
+ real(kind=real32) :: x
9
+ common/test/x
10
+ end module data
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/data_with_comments.f ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ BLOCK DATA PARAM_INI
2
+ COMMON /MYCOM/ MYTAB
3
+ INTEGER MYTAB(3)
4
+ DATA MYTAB/
5
+ * 0, ! 1 and more commenty stuff
6
+ * 4, ! 2
7
+ * 0 /
8
+ END
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/foo_deps.f90 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ module foo
2
+ type bar
3
+ character(len = 4) :: text
4
+ end type bar
5
+ type(bar), parameter :: abar = bar('abar')
6
+ end module foo
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module test_bug
2
+ implicit none
3
+ private
4
+ public :: intproduct
5
+
6
+ contains
7
+ integer function intproduct(a, b) result(res)
8
+ integer, intent(in) :: a, b
9
+ res = a*b
10
+ end function
11
+ end module
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/publicmod.f90 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ module foo
2
+ public
3
+ integer, private :: a
4
+ public :: setA
5
+ contains
6
+ subroutine setA(v)
7
+ integer, intent(in) :: v
8
+ a = v
9
+ end subroutine setA
10
+ end module foo
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/crackfortran/unicode_comment.f90 ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ subroutine foo(x)
2
+ real(8), intent(in) :: x
3
+ ! Écrit à l'écran la valeur de x
4
+ end subroutine
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/f2cmap/.f2py_f2cmap ADDED
@@ -0,0 +1 @@
 
 
1
+ dict(real=dict(real32='float', real64='double'), integer=dict(int64='long_long'))
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ subroutine func1(n, x, res)
2
+ use, intrinsic :: iso_fortran_env, only: int64, real64
3
+ implicit none
4
+ integer(int64), intent(in) :: n
5
+ real(real64), intent(in) :: x(n)
6
+ real(real64), intent(out) :: res
7
+ !f2py intent(hide) :: n
8
+ res = sum(x)
9
+ end
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/isocintrin/isoCtests.f90 ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module coddity
2
+ use iso_c_binding, only: c_double, c_int, c_int64_t
3
+ implicit none
4
+ contains
5
+ subroutine c_add(a, b, c) bind(c, name="c_add")
6
+ real(c_double), intent(in) :: a, b
7
+ real(c_double), intent(out) :: c
8
+ c = a + b
9
+ end subroutine c_add
10
+ ! gh-9693
11
+ function wat(x, y) result(z) bind(c)
12
+ integer(c_int), intent(in) :: x, y
13
+ integer(c_int) :: z
14
+
15
+ z = x + 7
16
+ end function wat
17
+ ! gh-25207
18
+ subroutine c_add_int64(a, b, c) bind(c)
19
+ integer(c_int64_t), intent(in) :: a, b
20
+ integer(c_int64_t), intent(out) :: c
21
+ c = a + b
22
+ end subroutine c_add_int64
23
+ ! gh-25207
24
+ subroutine add_arr(A, B, C)
25
+ integer(c_int64_t), intent(in) :: A(3)
26
+ integer(c_int64_t), intent(in) :: B(3)
27
+ integer(c_int64_t), intent(out) :: C(3)
28
+ integer :: j
29
+
30
+ do j = 1, 3
31
+ C(j) = A(j)+B(j)
32
+ end do
33
+ end subroutine
34
+ end module coddity
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/kind/foo.f90 ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ subroutine selectedrealkind(p, r, res)
4
+ implicit none
5
+
6
+ integer, intent(in) :: p, r
7
+ !f2py integer :: r=0
8
+ integer, intent(out) :: res
9
+ res = selected_real_kind(p, r)
10
+
11
+ end subroutine
12
+
13
+ subroutine selectedintkind(p, res)
14
+ implicit none
15
+
16
+ integer, intent(in) :: p
17
+ integer, intent(out) :: res
18
+ res = selected_int_kind(p)
19
+
20
+ end subroutine
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/mixed/foo.f ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ subroutine bar11(a)
2
+ cf2py intent(out) a
3
+ integer a
4
+ a = 11
5
+ end
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/mixed/foo_fixed.f90 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ module foo_fixed
2
+ contains
3
+ subroutine bar12(a)
4
+ !f2py intent(out) a
5
+ integer a
6
+ a = 12
7
+ end subroutine bar12
8
+ end module foo_fixed
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/mixed/foo_free.f90 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ module foo_free
2
+ contains
3
+ subroutine bar13(a)
4
+ !f2py intent(out) a
5
+ integer a
6
+ a = 13
7
+ end subroutine bar13
8
+ end module foo_free
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/module_data/mod.mod ADDED
Binary file (412 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/module_data/module_data_docstring.f90 ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module mod
2
+ integer :: i
3
+ integer :: x(4)
4
+ real, dimension(2,3) :: a
5
+ real, allocatable, dimension(:,:) :: b
6
+ contains
7
+ subroutine foo
8
+ integer :: k
9
+ k = 1
10
+ a(1,2) = a(1,2)+3
11
+ end subroutine foo
12
+ end module mod
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/negative_bounds/issue_20853.f90 ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ subroutine foo(is_, ie_, arr, tout)
2
+ implicit none
3
+ integer :: is_,ie_
4
+ real, intent(in) :: arr(is_:ie_)
5
+ real, intent(out) :: tout(is_:ie_)
6
+ tout = arr
7
+ end
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/quoted_character/foo.f ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SUBROUTINE FOO(OUT1, OUT2, OUT3, OUT4, OUT5, OUT6)
2
+ CHARACTER SINGLE, DOUBLE, SEMICOL, EXCLA, OPENPAR, CLOSEPAR
3
+ PARAMETER (SINGLE="'", DOUBLE='"', SEMICOL=';', EXCLA="!",
4
+ 1 OPENPAR="(", CLOSEPAR=")")
5
+ CHARACTER OUT1, OUT2, OUT3, OUT4, OUT5, OUT6
6
+ Cf2py intent(out) OUT1, OUT2, OUT3, OUT4, OUT5, OUT6
7
+ OUT1 = SINGLE
8
+ OUT2 = DOUBLE
9
+ OUT3 = SEMICOL
10
+ OUT4 = EXCLA
11
+ OUT5 = OPENPAR
12
+ OUT6 = CLOSEPAR
13
+ RETURN
14
+ END
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/regression/gh25337/data.f90 ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ module data
2
+ real(8) :: shift
3
+ contains
4
+ subroutine set_shift(in_shift)
5
+ real(8), intent(in) :: in_shift
6
+ shift = in_shift
7
+ end subroutine set_shift
8
+ end module data
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/regression/gh25337/use_data.f90 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ subroutine shift_a(dim_a, a)
2
+ use data, only: shift
3
+ integer, intent(in) :: dim_a
4
+ real(8), intent(inout), dimension(dim_a) :: a
5
+ a = a + shift
6
+ end subroutine shift_a
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/regression/inout.f90 ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ! Check that intent(in out) translates as intent(inout).
2
+ ! The separation seems to be a common usage.
3
+ subroutine foo(x)
4
+ implicit none
5
+ real(4), intent(in out) :: x
6
+ dimension x(3)
7
+ x(1) = x(1) + x(2) + x(3)
8
+ return
9
+ end
llmeval-env/lib/python3.10/site-packages/numpy/f2py/tests/src/return_complex/foo77.f ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ function t0(value)
2
+ complex value
3
+ complex t0
4
+ t0 = value
5
+ end
6
+ function t8(value)
7
+ complex*8 value
8
+ complex*8 t8
9
+ t8 = value
10
+ end
11
+ function t16(value)
12
+ complex*16 value
13
+ complex*16 t16
14
+ t16 = value
15
+ end
16
+ function td(value)
17
+ double complex value
18
+ double complex td
19
+ td = value
20
+ end
21
+
22
+ subroutine s0(t0,value)
23
+ complex value
24
+ complex t0
25
+ cf2py intent(out) t0
26
+ t0 = value
27
+ end
28
+ subroutine s8(t8,value)
29
+ complex*8 value
30
+ complex*8 t8
31
+ cf2py intent(out) t8
32
+ t8 = value
33
+ end
34
+ subroutine s16(t16,value)
35
+ complex*16 value
36
+ complex*16 t16
37
+ cf2py intent(out) t16
38
+ t16 = value
39
+ end
40
+ subroutine sd(td,value)
41
+ double complex value
42
+ double complex td
43
+ cf2py intent(out) td
44
+ td = value
45
+ end