Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/f2py/rules.py
7757 views
1
#!/usr/bin/env python3
2
"""
3
4
Rules for building C/API module with f2py2e.
5
6
Here is a skeleton of a new wrapper function (13Dec2001):
7
8
wrapper_function(args)
9
declarations
10
get_python_arguments, say, `a' and `b'
11
12
get_a_from_python
13
if (successful) {
14
15
get_b_from_python
16
if (successful) {
17
18
callfortran
19
if (successful) {
20
21
put_a_to_python
22
if (successful) {
23
24
put_b_to_python
25
if (successful) {
26
27
buildvalue = ...
28
29
}
30
31
}
32
33
}
34
35
}
36
cleanup_b
37
38
}
39
cleanup_a
40
41
return buildvalue
42
43
Copyright 1999,2000 Pearu Peterson all rights reserved,
44
Pearu Peterson <[email protected]>
45
Permission to use, modify, and distribute this software is given under the
46
terms of the NumPy License.
47
48
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
49
$Date: 2005/08/30 08:58:42 $
50
Pearu Peterson
51
52
"""
53
import os
54
import time
55
import copy
56
57
# __version__.version is now the same as the NumPy version
58
from . import __version__
59
f2py_version = __version__.version
60
numpy_version = __version__.version
61
62
from .auxfuncs import (
63
applyrules, debugcapi, dictappend, errmess, gentitle, getargs2,
64
hascallstatement, hasexternals, hasinitvalue, hasnote, hasresultnote,
65
isarray, isarrayofstrings, iscomplex, iscomplexarray,
66
iscomplexfunction, iscomplexfunction_warn, isdummyroutine, isexternal,
67
isfunction, isfunction_wrap, isint1array, isintent_aux, isintent_c,
68
isintent_callback, isintent_copy, isintent_hide, isintent_inout,
69
isintent_nothide, isintent_out, isintent_overwrite, islogical,
70
islong_complex, islong_double, islong_doublefunction, islong_long,
71
islong_longfunction, ismoduleroutine, isoptional, isrequired, isscalar,
72
issigned_long_longarray, isstring, isstringarray, isstringfunction,
73
issubroutine, issubroutine_wrap, isthreadsafe, isunsigned,
74
isunsigned_char, isunsigned_chararray, isunsigned_long_long,
75
isunsigned_long_longarray, isunsigned_short, isunsigned_shortarray,
76
l_and, l_not, l_or, outmess, replace, stripcomma, requiresf90wrapper
77
)
78
79
from . import capi_maps
80
from . import cfuncs
81
from . import common_rules
82
from . import use_rules
83
from . import f90mod_rules
84
from . import func2subr
85
86
options = {}
87
sepdict = {}
88
#for k in ['need_cfuncs']: sepdict[k]=','
89
for k in ['decl',
90
'frompyobj',
91
'cleanupfrompyobj',
92
'topyarr', 'method',
93
'pyobjfrom', 'closepyobjfrom',
94
'freemem',
95
'userincludes',
96
'includes0', 'includes', 'typedefs', 'typedefs_generated',
97
'cppmacros', 'cfuncs', 'callbacks',
98
'latexdoc',
99
'restdoc',
100
'routine_defs', 'externroutines',
101
'initf2pywraphooks',
102
'commonhooks', 'initcommonhooks',
103
'f90modhooks', 'initf90modhooks']:
104
sepdict[k] = '\n'
105
106
#################### Rules for C/API module #################
107
108
generationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
109
module_rules = {
110
'modulebody': """\
111
/* File: #modulename#module.c
112
* This file is auto-generated with f2py (version:#f2py_version#).
113
* f2py is a Fortran to Python Interface Generator (FPIG), Second Edition,
114
* written by Pearu Peterson <[email protected]>.
115
* Generation date: """ + time.asctime(time.gmtime(generationtime)) + """
116
* Do not edit this file directly unless you know what you are doing!!!
117
*/
118
119
#ifdef __cplusplus
120
extern \"C\" {
121
#endif
122
123
#ifndef PY_SSIZE_T_CLEAN
124
#define PY_SSIZE_T_CLEAN
125
#endif /* PY_SSIZE_T_CLEAN */
126
127
""" + gentitle("See f2py2e/cfuncs.py: includes") + """
128
#includes#
129
#includes0#
130
131
""" + gentitle("See f2py2e/rules.py: mod_rules['modulebody']") + """
132
static PyObject *#modulename#_error;
133
static PyObject *#modulename#_module;
134
135
""" + gentitle("See f2py2e/cfuncs.py: typedefs") + """
136
#typedefs#
137
138
""" + gentitle("See f2py2e/cfuncs.py: typedefs_generated") + """
139
#typedefs_generated#
140
141
""" + gentitle("See f2py2e/cfuncs.py: cppmacros") + """
142
#cppmacros#
143
144
""" + gentitle("See f2py2e/cfuncs.py: cfuncs") + """
145
#cfuncs#
146
147
""" + gentitle("See f2py2e/cfuncs.py: userincludes") + """
148
#userincludes#
149
150
""" + gentitle("See f2py2e/capi_rules.py: usercode") + """
151
#usercode#
152
153
/* See f2py2e/rules.py */
154
#externroutines#
155
156
""" + gentitle("See f2py2e/capi_rules.py: usercode1") + """
157
#usercode1#
158
159
""" + gentitle("See f2py2e/cb_rules.py: buildcallback") + """
160
#callbacks#
161
162
""" + gentitle("See f2py2e/rules.py: buildapi") + """
163
#body#
164
165
""" + gentitle("See f2py2e/f90mod_rules.py: buildhooks") + """
166
#f90modhooks#
167
168
""" + gentitle("See f2py2e/rules.py: module_rules['modulebody']") + """
169
170
""" + gentitle("See f2py2e/common_rules.py: buildhooks") + """
171
#commonhooks#
172
173
""" + gentitle("See f2py2e/rules.py") + """
174
175
static FortranDataDef f2py_routine_defs[] = {
176
#routine_defs#
177
{NULL}
178
};
179
180
static PyMethodDef f2py_module_methods[] = {
181
#pymethoddef#
182
{NULL,NULL}
183
};
184
185
static struct PyModuleDef moduledef = {
186
PyModuleDef_HEAD_INIT,
187
"#modulename#",
188
NULL,
189
-1,
190
f2py_module_methods,
191
NULL,
192
NULL,
193
NULL,
194
NULL
195
};
196
197
PyMODINIT_FUNC PyInit_#modulename#(void) {
198
int i;
199
PyObject *m,*d, *s, *tmp;
200
m = #modulename#_module = PyModule_Create(&moduledef);
201
Py_SET_TYPE(&PyFortran_Type, &PyType_Type);
202
import_array();
203
if (PyErr_Occurred())
204
{PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return m;}
205
d = PyModule_GetDict(m);
206
s = PyUnicode_FromString(\"#f2py_version#\");
207
PyDict_SetItemString(d, \"__version__\", s);
208
Py_DECREF(s);
209
s = PyUnicode_FromString(
210
\"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\");
211
PyDict_SetItemString(d, \"__doc__\", s);
212
Py_DECREF(s);
213
s = PyUnicode_FromString(\"""" + numpy_version + """\");
214
PyDict_SetItemString(d, \"__f2py_numpy_version__\", s);
215
Py_DECREF(s);
216
#modulename#_error = PyErr_NewException (\"#modulename#.error\", NULL, NULL);
217
/*
218
* Store the error object inside the dict, so that it could get deallocated.
219
* (in practice, this is a module, so it likely will not and cannot.)
220
*/
221
PyDict_SetItemString(d, \"_#modulename#_error\", #modulename#_error);
222
Py_DECREF(#modulename#_error);
223
for(i=0;f2py_routine_defs[i].name!=NULL;i++) {
224
tmp = PyFortranObject_NewAsAttr(&f2py_routine_defs[i]);
225
PyDict_SetItemString(d, f2py_routine_defs[i].name, tmp);
226
Py_DECREF(tmp);
227
}
228
#initf2pywraphooks#
229
#initf90modhooks#
230
#initcommonhooks#
231
#interface_usercode#
232
233
#ifdef F2PY_REPORT_ATEXIT
234
if (! PyErr_Occurred())
235
on_exit(f2py_report_on_exit,(void*)\"#modulename#\");
236
#endif
237
return m;
238
}
239
#ifdef __cplusplus
240
}
241
#endif
242
""",
243
'separatorsfor': {'latexdoc': '\n\n',
244
'restdoc': '\n\n'},
245
'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n',
246
'#modnote#\n',
247
'#latexdoc#'],
248
'restdoc': ['Module #modulename#\n' + '=' * 80,
249
'\n#restdoc#']
250
}
251
252
defmod_rules = [
253
{'body': '/*eof body*/',
254
'method': '/*eof method*/',
255
'externroutines': '/*eof externroutines*/',
256
'routine_defs': '/*eof routine_defs*/',
257
'initf90modhooks': '/*eof initf90modhooks*/',
258
'initf2pywraphooks': '/*eof initf2pywraphooks*/',
259
'initcommonhooks': '/*eof initcommonhooks*/',
260
'latexdoc': '',
261
'restdoc': '',
262
'modnote': {hasnote: '#note#', l_not(hasnote): ''},
263
}
264
]
265
266
routine_rules = {
267
'separatorsfor': sepdict,
268
'body': """
269
#begintitle#
270
static char doc_#apiname#[] = \"\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#\";
271
/* #declfortranroutine# */
272
static PyObject *#apiname#(const PyObject *capi_self,
273
PyObject *capi_args,
274
PyObject *capi_keywds,
275
#functype# (*f2py_func)(#callprotoargument#)) {
276
PyObject * volatile capi_buildvalue = NULL;
277
volatile int f2py_success = 1;
278
#decl#
279
static char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL};
280
#usercode#
281
#routdebugenter#
282
#ifdef F2PY_REPORT_ATEXIT
283
f2py_start_clock();
284
#endif
285
if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\
286
\"#argformat#|#keyformat##xaformat#:#pyname#\",\\
287
capi_kwlist#args_capi##keys_capi##keys_xa#))\n return NULL;
288
#frompyobj#
289
/*end of frompyobj*/
290
#ifdef F2PY_REPORT_ATEXIT
291
f2py_start_call_clock();
292
#endif
293
#callfortranroutine#
294
if (PyErr_Occurred())
295
f2py_success = 0;
296
#ifdef F2PY_REPORT_ATEXIT
297
f2py_stop_call_clock();
298
#endif
299
/*end of callfortranroutine*/
300
if (f2py_success) {
301
#pyobjfrom#
302
/*end of pyobjfrom*/
303
CFUNCSMESS(\"Building return value.\\n\");
304
capi_buildvalue = Py_BuildValue(\"#returnformat#\"#return#);
305
/*closepyobjfrom*/
306
#closepyobjfrom#
307
} /*if (f2py_success) after callfortranroutine*/
308
/*cleanupfrompyobj*/
309
#cleanupfrompyobj#
310
if (capi_buildvalue == NULL) {
311
#routdebugfailure#
312
} else {
313
#routdebugleave#
314
}
315
CFUNCSMESS(\"Freeing memory.\\n\");
316
#freemem#
317
#ifdef F2PY_REPORT_ATEXIT
318
f2py_stop_clock();
319
#endif
320
return capi_buildvalue;
321
}
322
#endtitle#
323
""",
324
'routine_defs': '#routine_def#',
325
'initf2pywraphooks': '#initf2pywraphook#',
326
'externroutines': '#declfortranroutine#',
327
'doc': '#docreturn##name#(#docsignature#)',
328
'docshort': '#docreturn##name#(#docsignatureshort#)',
329
'docs': '" #docreturn##name#(#docsignature#)\\n"\n',
330
'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'],
331
'cppmacros': {debugcapi: '#define DEBUGCFUNCS'},
332
'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n',
333
"""
334
\\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)}
335
#routnote#
336
337
#latexdocstrsigns#
338
"""],
339
'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80,
340
341
]
342
}
343
344
################## Rules for C/API function ##############
345
346
rout_rules = [
347
{ # Init
348
'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n',
349
'routdebugleave': '\n', 'routdebugfailure': '\n',
350
'setjmpbuf': ' || ',
351
'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n',
352
'docstrcbs': '\n', 'docstrsigns': '\\n"\n"',
353
'latexdocstrsigns': '\n',
354
'latexdocstrreq': '\n', 'latexdocstropt': '\n',
355
'latexdocstrout': '\n', 'latexdocstrcbs': '\n',
356
},
357
'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '',
358
'docsign': '', 'docsignopt': '', 'decl': '/*decl*/',
359
'freemem': '/*freemem*/',
360
'docsignshort': '', 'docsignoptshort': '',
361
'docstrsigns': '', 'latexdocstrsigns': '',
362
'docstrreq': '\\nParameters\\n----------',
363
'docstropt': '\\nOther Parameters\\n----------------',
364
'docstrout': '\\nReturns\\n-------',
365
'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n',
366
'latexdocstrreq': '\\noindent Required arguments:',
367
'latexdocstropt': '\\noindent Optional arguments:',
368
'latexdocstrout': '\\noindent Return objects:',
369
'latexdocstrcbs': '\\noindent Call-back functions:',
370
'args_capi': '', 'keys_capi': '', 'functype': '',
371
'frompyobj': '/*frompyobj*/',
372
# this list will be reversed
373
'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'],
374
'pyobjfrom': '/*pyobjfrom*/',
375
# this list will be reversed
376
'closepyobjfrom': ['/*end of closepyobjfrom*/'],
377
'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/',
378
'routdebugenter': '/*routdebugenter*/',
379
'routdebugfailure': '/*routdebugfailure*/',
380
'callfortranroutine': '/*callfortranroutine*/',
381
'argformat': '', 'keyformat': '', 'need_cfuncs': '',
382
'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '',
383
'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '',
384
'initf2pywraphook': '',
385
'routnote': {hasnote: '--- #note#', l_not(hasnote): ''},
386
}, {
387
'apiname': 'f2py_rout_#modulename#_#name#',
388
'pyname': '#modulename#.#name#',
389
'decl': '',
390
'_check': l_not(ismoduleroutine)
391
}, {
392
'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#',
393
'pyname': '#modulename#.#f90modulename#.#name#',
394
'decl': '',
395
'_check': ismoduleroutine
396
}, { # Subroutine
397
'functype': 'void',
398
'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
399
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);',
400
ismoduleroutine: '',
401
isdummyroutine: ''
402
},
403
'routine_def': {l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)): ' {\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},',
404
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): ' {\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},',
405
l_and(l_not(ismoduleroutine), isdummyroutine): ' {\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},',
406
},
407
'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'},
408
'callfortranroutine': [
409
{debugcapi: [
410
""" fprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]},
411
{hasexternals: """\
412
if (#setjmpbuf#) {
413
f2py_success = 0;
414
} else {"""},
415
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
416
{hascallstatement: ''' #callstatement#;
417
/*(*f2py_func)(#callfortran#);*/'''},
418
{l_not(l_or(hascallstatement, isdummyroutine))
419
: ' (*f2py_func)(#callfortran#);'},
420
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
421
{hasexternals: """ }"""}
422
],
423
'_check': l_and(issubroutine, l_not(issubroutine_wrap)),
424
}, { # Wrapped function
425
'functype': 'void',
426
'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',
427
isdummyroutine: '',
428
},
429
430
'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): ' {\"#name#\",-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},',
431
isdummyroutine: ' {\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},',
432
},
433
'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '''
434
{
435
extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void);
436
PyObject* o = PyDict_GetItemString(d,"#name#");
437
tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL);
438
PyObject_SetAttrString(o,"_cpointer", tmp);
439
Py_DECREF(tmp);
440
s = PyUnicode_FromString("#name#");
441
PyObject_SetAttrString(o,"__name__", s);
442
Py_DECREF(s);
443
}
444
'''},
445
'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},
446
'callfortranroutine': [
447
{debugcapi: [
448
""" fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},
449
{hasexternals: """\
450
if (#setjmpbuf#) {
451
f2py_success = 0;
452
} else {"""},
453
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
454
{l_not(l_or(hascallstatement, isdummyroutine))
455
: ' (*f2py_func)(#callfortran#);'},
456
{hascallstatement:
457
' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'},
458
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
459
{hasexternals: ' }'}
460
],
461
'_check': isfunction_wrap,
462
}, { # Wrapped subroutine
463
'functype': 'void',
464
'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',
465
isdummyroutine: '',
466
},
467
468
'routine_def': {l_not(l_or(ismoduleroutine, isdummyroutine)): ' {\"#name#\",-1,{{-1}},0,(char *)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),(f2py_init_func)#apiname#,doc_#apiname#},',
469
isdummyroutine: ' {\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},',
470
},
471
'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '''
472
{
473
extern void #F_FUNC#(#name_lower#,#NAME#)(void);
474
PyObject* o = PyDict_GetItemString(d,"#name#");
475
tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL);
476
PyObject_SetAttrString(o,"_cpointer", tmp);
477
Py_DECREF(tmp);
478
s = PyUnicode_FromString("#name#");
479
PyObject_SetAttrString(o,"__name__", s);
480
Py_DECREF(s);
481
}
482
'''},
483
'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},
484
'callfortranroutine': [
485
{debugcapi: [
486
""" fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},
487
{hasexternals: """\
488
if (#setjmpbuf#) {
489
f2py_success = 0;
490
} else {"""},
491
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
492
{l_not(l_or(hascallstatement, isdummyroutine))
493
: ' (*f2py_func)(#callfortran#);'},
494
{hascallstatement:
495
' #callstatement#;\n /*(*f2py_func)(#callfortran#);*/'},
496
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
497
{hasexternals: ' }'}
498
],
499
'_check': issubroutine_wrap,
500
}, { # Function
501
'functype': '#ctype#',
502
'docreturn': {l_not(isintent_hide): '#rname#,'},
503
'docstrout': '#pydocsignout#',
504
'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}',
505
{hasresultnote: '--- #resultnote#'}],
506
'callfortranroutine': [{l_and(debugcapi, isstringfunction): """\
507
#ifdef USESCOMPAQFORTRAN
508
fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n\");
509
#else
510
fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\");
511
#endif
512
"""},
513
{l_and(debugcapi, l_not(isstringfunction)): """\
514
fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\");
515
"""}
516
],
517
'_check': l_and(isfunction, l_not(isfunction_wrap))
518
}, { # Scalar function
519
'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
520
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);',
521
isdummyroutine: ''
522
},
523
'routine_def': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): ' {\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},',
524
l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): ' {\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},',
525
isdummyroutine: ' {\"#name#\",-1,{{-1}},0,NULL,(f2py_init_func)#apiname#,doc_#apiname#},',
526
},
527
'decl': [{iscomplexfunction_warn: ' #ctype# #name#_return_value={0,0};',
528
l_not(iscomplexfunction): ' #ctype# #name#_return_value=0;'},
529
{iscomplexfunction:
530
' PyObject *#name#_return_value_capi = Py_None;'}
531
],
532
'callfortranroutine': [
533
{hasexternals: """\
534
if (#setjmpbuf#) {
535
f2py_success = 0;
536
} else {"""},
537
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
538
{hascallstatement: ''' #callstatement#;
539
/* #name#_return_value = (*f2py_func)(#callfortran#);*/
540
'''},
541
{l_not(l_or(hascallstatement, isdummyroutine))
542
: ' #name#_return_value = (*f2py_func)(#callfortran#);'},
543
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
544
{hasexternals: ' }'},
545
{l_and(debugcapi, iscomplexfunction)
546
: ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'},
547
{l_and(debugcapi, l_not(iscomplexfunction)): ' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}],
548
'pyobjfrom': {iscomplexfunction: ' #name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'},
549
'need': [{l_not(isdummyroutine): 'F_FUNC'},
550
{iscomplexfunction: 'pyobj_from_#ctype#1'},
551
{islong_longfunction: 'long_long'},
552
{islong_doublefunction: 'long_double'}],
553
'returnformat': {l_not(isintent_hide): '#rformat#'},
554
'return': {iscomplexfunction: ',#name#_return_value_capi',
555
l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'},
556
'_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap))
557
}, { # String function # in use for --no-wrap
558
'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
559
'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)):
560
' {\"#name#\",-1,{{-1}},0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},',
561
l_and(l_not(ismoduleroutine), isintent_c):
562
' {\"#name#\",-1,{{-1}},0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},'
563
},
564
'decl': [' #ctype# #name#_return_value = NULL;',
565
' int #name#_return_value_len = 0;'],
566
'callfortran':'#name#_return_value,#name#_return_value_len,',
567
'callfortranroutine':[' #name#_return_value_len = #rlength#;',
568
' if ((#name#_return_value = (string)malloc('
569
+ '#name#_return_value_len+1) == NULL) {',
570
' PyErr_SetString(PyExc_MemoryError, \"out of memory\");',
571
' f2py_success = 0;',
572
' } else {',
573
" (#name#_return_value)[#name#_return_value_len] = '\\0';",
574
' }',
575
' if (f2py_success) {',
576
{hasexternals: """\
577
if (#setjmpbuf#) {
578
f2py_success = 0;
579
} else {"""},
580
{isthreadsafe: ' Py_BEGIN_ALLOW_THREADS'},
581
"""\
582
#ifdef USESCOMPAQFORTRAN
583
(*f2py_func)(#callcompaqfortran#);
584
#else
585
(*f2py_func)(#callfortran#);
586
#endif
587
""",
588
{isthreadsafe: ' Py_END_ALLOW_THREADS'},
589
{hasexternals: ' }'},
590
{debugcapi:
591
' fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'},
592
' } /* if (f2py_success) after (string)malloc */',
593
],
594
'returnformat': '#rformat#',
595
'return': ',#name#_return_value',
596
'freemem': ' STRINGFREE(#name#_return_value);',
597
'need': ['F_FUNC', '#ctype#', 'STRINGFREE'],
598
'_check':l_and(isstringfunction, l_not(isfunction_wrap)) # ???obsolete
599
},
600
{ # Debugging
601
'routdebugenter': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");',
602
'routdebugleave': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");',
603
'routdebugfailure': ' fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");',
604
'_check': debugcapi
605
}
606
]
607
608
################ Rules for arguments ##################
609
610
typedef_need_dict = {islong_long: 'long_long',
611
islong_double: 'long_double',
612
islong_complex: 'complex_long_double',
613
isunsigned_char: 'unsigned_char',
614
isunsigned_short: 'unsigned_short',
615
isunsigned: 'unsigned',
616
isunsigned_long_long: 'unsigned_long_long',
617
isunsigned_chararray: 'unsigned_char',
618
isunsigned_shortarray: 'unsigned_short',
619
isunsigned_long_longarray: 'unsigned_long_long',
620
issigned_long_longarray: 'long_long',
621
}
622
623
aux_rules = [
624
{
625
'separatorsfor': sepdict
626
},
627
{ # Common
628
'frompyobj': [' /* Processing auxiliary variable #varname# */',
629
{debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ],
630
'cleanupfrompyobj': ' /* End of cleaning variable #varname# */',
631
'need': typedef_need_dict,
632
},
633
# Scalars (not complex)
634
{ # Common
635
'decl': ' #ctype# #varname# = 0;',
636
'need': {hasinitvalue: 'math.h'},
637
'frompyobj': {hasinitvalue: ' #varname# = #init#;'},
638
'_check': l_and(isscalar, l_not(iscomplex)),
639
},
640
{
641
'return': ',#varname#',
642
'docstrout': '#pydocsignout#',
643
'docreturn': '#outvarname#,',
644
'returnformat': '#varrformat#',
645
'_check': l_and(isscalar, l_not(iscomplex), isintent_out),
646
},
647
# Complex scalars
648
{ # Common
649
'decl': ' #ctype# #varname#;',
650
'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'},
651
'_check': iscomplex
652
},
653
# String
654
{ # Common
655
'decl': [' #ctype# #varname# = NULL;',
656
' int slen(#varname#);',
657
],
658
'need':['len..'],
659
'_check':isstring
660
},
661
# Array
662
{ # Common
663
'decl': [' #ctype# *#varname# = NULL;',
664
' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',
665
' const int #varname#_Rank = #rank#;',
666
],
667
'need':['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],
668
'_check': isarray
669
},
670
# Scalararray
671
{ # Common
672
'_check': l_and(isarray, l_not(iscomplexarray))
673
}, { # Not hidden
674
'_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)
675
},
676
# Integer*1 array
677
{'need': '#ctype#',
678
'_check': isint1array,
679
'_depend': ''
680
},
681
# Integer*-1 array
682
{'need': '#ctype#',
683
'_check': isunsigned_chararray,
684
'_depend': ''
685
},
686
# Integer*-2 array
687
{'need': '#ctype#',
688
'_check': isunsigned_shortarray,
689
'_depend': ''
690
},
691
# Integer*-8 array
692
{'need': '#ctype#',
693
'_check': isunsigned_long_longarray,
694
'_depend': ''
695
},
696
# Complexarray
697
{'need': '#ctype#',
698
'_check': iscomplexarray,
699
'_depend': ''
700
},
701
# Stringarray
702
{
703
'callfortranappend': {isarrayofstrings: 'flen(#varname#),'},
704
'need': 'string',
705
'_check': isstringarray
706
}
707
]
708
709
arg_rules = [
710
{
711
'separatorsfor': sepdict
712
},
713
{ # Common
714
'frompyobj': [' /* Processing variable #varname# */',
715
{debugcapi: ' fprintf(stderr,"#vardebuginfo#\\n");'}, ],
716
'cleanupfrompyobj': ' /* End of cleaning variable #varname# */',
717
'_depend': '',
718
'need': typedef_need_dict,
719
},
720
# Doc signatures
721
{
722
'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'},
723
'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'},
724
'docstrout': {isintent_out: '#pydocsignout#'},
725
'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
726
{hasnote: '--- #note#'}]},
727
'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
728
{hasnote: '--- #note#'}]},
729
'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}',
730
{l_and(hasnote, isintent_hide): '--- #note#',
731
l_and(hasnote, isintent_nothide): '--- See above.'}]},
732
'depend': ''
733
},
734
# Required/Optional arguments
735
{
736
'kwlist': '"#varname#",',
737
'docsign': '#varname#,',
738
'_check': l_and(isintent_nothide, l_not(isoptional))
739
},
740
{
741
'kwlistopt': '"#varname#",',
742
'docsignopt': '#varname#=#showinit#,',
743
'docsignoptshort': '#varname#,',
744
'_check': l_and(isintent_nothide, isoptional)
745
},
746
# Docstring/BuildValue
747
{
748
'docreturn': '#outvarname#,',
749
'returnformat': '#varrformat#',
750
'_check': isintent_out
751
},
752
# Externals (call-back functions)
753
{ # Common
754
'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'},
755
'docsignxashort': {isintent_nothide: '#varname#_extra_args,'},
756
'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n Default: ()'},
757
'docstrcbs': '#cbdocstr#',
758
'latexdocstrcbs': '\\item[] #cblatexdocstr#',
759
'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'},
760
'decl': [' #cbname#_t #varname#_cb = { Py_None, NULL, 0 };',
761
' #cbname#_t *#varname#_cb_ptr = &#varname#_cb;',
762
' PyTupleObject *#varname#_xa_capi = NULL;',
763
{l_not(isintent_callback):
764
' #cbname#_typedef #varname#_cptr;'}
765
],
766
'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'},
767
'argformat': {isrequired: 'O'},
768
'keyformat': {isoptional: 'O'},
769
'xaformat': {isintent_nothide: 'O!'},
770
'args_capi': {isrequired: ',&#varname#_cb.capi'},
771
'keys_capi': {isoptional: ',&#varname#_cb.capi'},
772
'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi',
773
'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))',
774
'callfortran': {l_not(isintent_callback): '#varname#_cptr,'},
775
'need': ['#cbname#', 'setjmp.h'],
776
'_check':isexternal
777
},
778
{
779
'frompyobj': [{l_not(isintent_callback): """\
780
if(F2PyCapsule_Check(#varname#_cb.capi)) {
781
#varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi);
782
} else {
783
#varname#_cptr = #cbname#;
784
}
785
"""}, {isintent_callback: """\
786
if (#varname#_cb.capi==Py_None) {
787
#varname#_cb.capi = PyObject_GetAttrString(#modulename#_module,\"#varname#\");
788
if (#varname#_cb.capi) {
789
if (#varname#_xa_capi==NULL) {
790
if (PyObject_HasAttrString(#modulename#_module,\"#varname#_extra_args\")) {
791
PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#varname#_extra_args\");
792
if (capi_tmp) {
793
#varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp);
794
Py_DECREF(capi_tmp);
795
}
796
else {
797
#varname#_xa_capi = (PyTupleObject *)Py_BuildValue(\"()\");
798
}
799
if (#varname#_xa_capi==NULL) {
800
PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n\");
801
return NULL;
802
}
803
}
804
}
805
}
806
if (#varname#_cb.capi==NULL) {
807
PyErr_SetString(#modulename#_error,\"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n\");
808
return NULL;
809
}
810
}
811
"""},
812
"""\
813
if (create_cb_arglist(#varname#_cb.capi,#varname#_xa_capi,#maxnofargs#,#nofoptargs#,&#varname#_cb.nofargs,&#varname#_cb.args_capi,\"failed in processing argument list for call-back #varname#.\")) {
814
""",
815
{debugcapi: ["""\
816
fprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#varname#_cb.nofargs);
817
CFUNCSMESSPY(\"for #varname#=\",#varname#_cb.capi);""",
818
{l_not(isintent_callback): """ fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]},
819
"""\
820
CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\");
821
#varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""",
822
],
823
'cleanupfrompyobj':
824
"""\
825
CFUNCSMESS(\"Restoring callback variables for `#varname#`.\\n\");
826
#varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);
827
Py_DECREF(#varname#_cb.args_capi);
828
}""",
829
'need': ['SWAP', 'create_cb_arglist'],
830
'_check':isexternal,
831
'_depend':''
832
},
833
# Scalars (not complex)
834
{ # Common
835
'decl': ' #ctype# #varname# = 0;',
836
'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},
837
'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'},
838
'return': {isintent_out: ',#varname#'},
839
'_check': l_and(isscalar, l_not(iscomplex))
840
}, {
841
'need': {hasinitvalue: 'math.h'},
842
'_check': l_and(isscalar, l_not(iscomplex)),
843
}, { # Not hidden
844
'decl': ' PyObject *#varname#_capi = Py_None;',
845
'argformat': {isrequired: 'O'},
846
'keyformat': {isoptional: 'O'},
847
'args_capi': {isrequired: ',&#varname#_capi'},
848
'keys_capi': {isoptional: ',&#varname#_capi'},
849
'pyobjfrom': {isintent_inout: """\
850
f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);
851
if (f2py_success) {"""},
852
'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"},
853
'need': {isintent_inout: 'try_pyarr_from_#ctype#'},
854
'_check': l_and(isscalar, l_not(iscomplex), isintent_nothide)
855
}, {
856
'frompyobj': [
857
# hasinitvalue...
858
# if pyobj is None:
859
# varname = init
860
# else
861
# from_pyobj(varname)
862
#
863
# isoptional and noinitvalue...
864
# if pyobj is not None:
865
# from_pyobj(varname)
866
# else:
867
# varname is uninitialized
868
#
869
# ...
870
# from_pyobj(varname)
871
#
872
{hasinitvalue: ' if (#varname#_capi == Py_None) #varname# = #init#; else',
873
'_depend': ''},
874
{l_and(isoptional, l_not(hasinitvalue)): ' if (#varname#_capi != Py_None)',
875
'_depend': ''},
876
{l_not(islogical): '''\
877
f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");
878
if (f2py_success) {'''},
879
{islogical: '''\
880
#varname# = (#ctype#)PyObject_IsTrue(#varname#_capi);
881
f2py_success = 1;
882
if (f2py_success) {'''},
883
],
884
'cleanupfrompyobj': ' } /*if (f2py_success) of #varname#*/',
885
'need': {l_not(islogical): '#ctype#_from_pyobj'},
886
'_check': l_and(isscalar, l_not(iscomplex), isintent_nothide),
887
'_depend': ''
888
}, { # Hidden
889
'frompyobj': {hasinitvalue: ' #varname# = #init#;'},
890
'need': typedef_need_dict,
891
'_check': l_and(isscalar, l_not(iscomplex), isintent_hide),
892
'_depend': ''
893
}, { # Common
894
'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},
895
'_check': l_and(isscalar, l_not(iscomplex)),
896
'_depend': ''
897
},
898
# Complex scalars
899
{ # Common
900
'decl': ' #ctype# #varname#;',
901
'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'},
902
'pyobjfrom': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},
903
'return': {isintent_out: ',#varname#_capi'},
904
'_check': iscomplex
905
}, { # Not hidden
906
'decl': ' PyObject *#varname#_capi = Py_None;',
907
'argformat': {isrequired: 'O'},
908
'keyformat': {isoptional: 'O'},
909
'args_capi': {isrequired: ',&#varname#_capi'},
910
'keys_capi': {isoptional: ',&#varname#_capi'},
911
'need': {isintent_inout: 'try_pyarr_from_#ctype#'},
912
'pyobjfrom': {isintent_inout: """\
913
f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);
914
if (f2py_success) {"""},
915
'closepyobjfrom': {isintent_inout: " } /*if (f2py_success) of #varname# pyobjfrom*/"},
916
'_check': l_and(iscomplex, isintent_nothide)
917
}, {
918
'frompyobj': [{hasinitvalue: ' if (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'},
919
{l_and(isoptional, l_not(hasinitvalue))
920
: ' if (#varname#_capi != Py_None)'},
921
' f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");'
922
'\n if (f2py_success) {'],
923
'cleanupfrompyobj': ' } /*if (f2py_success) of #varname# frompyobj*/',
924
'need': ['#ctype#_from_pyobj'],
925
'_check': l_and(iscomplex, isintent_nothide),
926
'_depend': ''
927
}, { # Hidden
928
'decl': {isintent_out: ' PyObject *#varname#_capi = Py_None;'},
929
'_check': l_and(iscomplex, isintent_hide)
930
}, {
931
'frompyobj': {hasinitvalue: ' #varname#.r = #init.r#, #varname#.i = #init.i#;'},
932
'_check': l_and(iscomplex, isintent_hide),
933
'_depend': ''
934
}, { # Common
935
'pyobjfrom': {isintent_out: ' #varname#_capi = pyobj_from_#ctype#1(#varname#);'},
936
'need': ['pyobj_from_#ctype#1'],
937
'_check': iscomplex
938
}, {
939
'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},
940
'_check': iscomplex,
941
'_depend': ''
942
},
943
# String
944
{ # Common
945
'decl': [' #ctype# #varname# = NULL;',
946
' int slen(#varname#);',
947
' PyObject *#varname#_capi = Py_None;'],
948
'callfortran':'#varname#,',
949
'callfortranappend':'slen(#varname#),',
950
'pyobjfrom':[
951
{debugcapi:
952
' fprintf(stderr,'
953
'"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},
954
# The trailing null value for Fortran is blank.
955
{l_and(isintent_out, l_not(isintent_c)):
956
" STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},
957
],
958
'return': {isintent_out: ',#varname#'},
959
'need': ['len..',
960
{l_and(isintent_out, l_not(isintent_c)): 'STRINGPADN'}],
961
'_check':isstring
962
}, { # Common
963
'frompyobj': [
964
"""\
965
slen(#varname#) = #length#;
966
f2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,"""
967
"""#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth#"""
968
"""`#varname#\' of #pyname# to C #ctype#\");
969
if (f2py_success) {""",
970
# The trailing null value for Fortran is blank.
971
{l_not(isintent_c):
972
" STRINGPADN(#varname#, slen(#varname#), '\\0', ' ');"},
973
],
974
'cleanupfrompyobj': """\
975
STRINGFREE(#varname#);
976
} /*if (f2py_success) of #varname#*/""",
977
'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE',
978
{l_not(isintent_c): 'STRINGPADN'}],
979
'_check':isstring,
980
'_depend':''
981
}, { # Not hidden
982
'argformat': {isrequired: 'O'},
983
'keyformat': {isoptional: 'O'},
984
'args_capi': {isrequired: ',&#varname#_capi'},
985
'keys_capi': {isoptional: ',&#varname#_capi'},
986
'pyobjfrom': [
987
{l_and(isintent_inout, l_not(isintent_c)):
988
" STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},
989
{isintent_inout: '''\
990
f2py_success = try_pyarr_from_#ctype#(#varname#_capi, #varname#,
991
slen(#varname#));
992
if (f2py_success) {'''}],
993
'closepyobjfrom': {isintent_inout: ' } /*if (f2py_success) of #varname# pyobjfrom*/'},
994
'need': {isintent_inout: 'try_pyarr_from_#ctype#',
995
l_and(isintent_inout, l_not(isintent_c)): 'STRINGPADN'},
996
'_check': l_and(isstring, isintent_nothide)
997
}, { # Hidden
998
'_check': l_and(isstring, isintent_hide)
999
}, {
1000
'frompyobj': {debugcapi: ' fprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},
1001
'_check': isstring,
1002
'_depend': ''
1003
},
1004
# Array
1005
{ # Common
1006
'decl': [' #ctype# *#varname# = NULL;',
1007
' npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',
1008
' const int #varname#_Rank = #rank#;',
1009
' PyArrayObject *capi_#varname#_tmp = NULL;',
1010
' int capi_#varname#_intent = 0;',
1011
],
1012
'callfortran':'#varname#,',
1013
'return':{isintent_out: ',capi_#varname#_tmp'},
1014
'need': 'len..',
1015
'_check': isarray
1016
}, { # intent(overwrite) array
1017
'decl': ' int capi_overwrite_#varname# = 1;',
1018
'kwlistxa': '"overwrite_#varname#",',
1019
'xaformat': 'i',
1020
'keys_xa': ',&capi_overwrite_#varname#',
1021
'docsignxa': 'overwrite_#varname#=1,',
1022
'docsignxashort': 'overwrite_#varname#,',
1023
'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 1',
1024
'_check': l_and(isarray, isintent_overwrite),
1025
}, {
1026
'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',
1027
'_check': l_and(isarray, isintent_overwrite),
1028
'_depend': '',
1029
},
1030
{ # intent(copy) array
1031
'decl': ' int capi_overwrite_#varname# = 0;',
1032
'kwlistxa': '"overwrite_#varname#",',
1033
'xaformat': 'i',
1034
'keys_xa': ',&capi_overwrite_#varname#',
1035
'docsignxa': 'overwrite_#varname#=0,',
1036
'docsignxashort': 'overwrite_#varname#,',
1037
'docstropt': 'overwrite_#varname# : input int, optional\\n Default: 0',
1038
'_check': l_and(isarray, isintent_copy),
1039
}, {
1040
'frompyobj': ' capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',
1041
'_check': l_and(isarray, isintent_copy),
1042
'_depend': '',
1043
}, {
1044
'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],
1045
'_check': isarray,
1046
'_depend': ''
1047
}, { # Not hidden
1048
'decl': ' PyObject *#varname#_capi = Py_None;',
1049
'argformat': {isrequired: 'O'},
1050
'keyformat': {isoptional: 'O'},
1051
'args_capi': {isrequired: ',&#varname#_capi'},
1052
'keys_capi': {isoptional: ',&#varname#_capi'},
1053
'_check': l_and(isarray, isintent_nothide)
1054
}, {
1055
'frompyobj': [' #setdims#;',
1056
' capi_#varname#_intent |= #intent#;',
1057
{isintent_hide:
1058
' capi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,Py_None);'},
1059
{isintent_nothide:
1060
' capi_#varname#_tmp = array_from_pyobj(#atype#,#varname#_Dims,#varname#_Rank,capi_#varname#_intent,#varname#_capi);'},
1061
"""\
1062
if (capi_#varname#_tmp == NULL) {
1063
PyObject *exc, *val, *tb;
1064
PyErr_Fetch(&exc, &val, &tb);
1065
PyErr_SetString(exc ? exc : #modulename#_error,\"failed in converting #nth# `#varname#\' of #pyname# to C/Fortran array\" );
1066
npy_PyErr_ChainExceptionsCause(exc, val, tb);
1067
} else {
1068
#varname# = (#ctype# *)(PyArray_DATA(capi_#varname#_tmp));
1069
""",
1070
{hasinitvalue: [
1071
{isintent_nothide:
1072
' if (#varname#_capi == Py_None) {'},
1073
{isintent_hide: ' {'},
1074
{iscomplexarray: ' #ctype# capi_c;'},
1075
"""\
1076
int *_i,capi_i=0;
1077
CFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\");
1078
if (initforcomb(PyArray_DIMS(capi_#varname#_tmp),PyArray_NDIM(capi_#varname#_tmp),1)) {
1079
while ((_i = nextforcomb()))
1080
#varname#[capi_i++] = #init#; /* fortran way */
1081
} else {
1082
PyObject *exc, *val, *tb;
1083
PyErr_Fetch(&exc, &val, &tb);
1084
PyErr_SetString(exc ? exc : #modulename#_error,\"Initialization of #nth# #varname# failed (initforcomb).\");
1085
npy_PyErr_ChainExceptionsCause(exc, val, tb);
1086
f2py_success = 0;
1087
}
1088
}
1089
if (f2py_success) {"""]},
1090
],
1091
'cleanupfrompyobj': [ # note that this list will be reversed
1092
' } /*if (capi_#varname#_tmp == NULL) ... else of #varname#*/',
1093
{l_not(l_or(isintent_out, isintent_hide)): """\
1094
if((PyObject *)capi_#varname#_tmp!=#varname#_capi) {
1095
Py_XDECREF(capi_#varname#_tmp); }"""},
1096
{l_and(isintent_hide, l_not(isintent_out))
1097
: """ Py_XDECREF(capi_#varname#_tmp);"""},
1098
{hasinitvalue: ' } /*if (f2py_success) of #varname# init*/'},
1099
],
1100
'_check': isarray,
1101
'_depend': ''
1102
},
1103
# Scalararray
1104
{ # Common
1105
'_check': l_and(isarray, l_not(iscomplexarray))
1106
}, { # Not hidden
1107
'_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)
1108
},
1109
# Integer*1 array
1110
{'need': '#ctype#',
1111
'_check': isint1array,
1112
'_depend': ''
1113
},
1114
# Integer*-1 array
1115
{'need': '#ctype#',
1116
'_check': isunsigned_chararray,
1117
'_depend': ''
1118
},
1119
# Integer*-2 array
1120
{'need': '#ctype#',
1121
'_check': isunsigned_shortarray,
1122
'_depend': ''
1123
},
1124
# Integer*-8 array
1125
{'need': '#ctype#',
1126
'_check': isunsigned_long_longarray,
1127
'_depend': ''
1128
},
1129
# Complexarray
1130
{'need': '#ctype#',
1131
'_check': iscomplexarray,
1132
'_depend': ''
1133
},
1134
# Stringarray
1135
{
1136
'callfortranappend': {isarrayofstrings: 'flen(#varname#),'},
1137
'need': 'string',
1138
'_check': isstringarray
1139
}
1140
]
1141
1142
################# Rules for checking ###############
1143
1144
check_rules = [
1145
{
1146
'frompyobj': {debugcapi: ' fprintf(stderr,\"debug-capi:Checking `#check#\'\\n\");'},
1147
'need': 'len..'
1148
}, {
1149
'frompyobj': ' CHECKSCALAR(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {',
1150
'cleanupfrompyobj': ' } /*CHECKSCALAR(#check#)*/',
1151
'need': 'CHECKSCALAR',
1152
'_check': l_and(isscalar, l_not(iscomplex)),
1153
'_break': ''
1154
}, {
1155
'frompyobj': ' CHECKSTRING(#check#,\"#check#\",\"#nth# #varname#\",\"#varshowvalue#\",#varname#) {',
1156
'cleanupfrompyobj': ' } /*CHECKSTRING(#check#)*/',
1157
'need': 'CHECKSTRING',
1158
'_check': isstring,
1159
'_break': ''
1160
}, {
1161
'need': 'CHECKARRAY',
1162
'frompyobj': ' CHECKARRAY(#check#,\"#check#\",\"#nth# #varname#\") {',
1163
'cleanupfrompyobj': ' } /*CHECKARRAY(#check#)*/',
1164
'_check': isarray,
1165
'_break': ''
1166
}, {
1167
'need': 'CHECKGENERIC',
1168
'frompyobj': ' CHECKGENERIC(#check#,\"#check#\",\"#nth# #varname#\") {',
1169
'cleanupfrompyobj': ' } /*CHECKGENERIC(#check#)*/',
1170
}
1171
]
1172
1173
########## Applying the rules. No need to modify what follows #############
1174
1175
#################### Build C/API module #######################
1176
1177
1178
def buildmodule(m, um):
1179
"""
1180
Return
1181
"""
1182
outmess(' Building module "%s"...\n' % (m['name']))
1183
ret = {}
1184
mod_rules = defmod_rules[:]
1185
vrd = capi_maps.modsign2map(m)
1186
rd = dictappend({'f2py_version': f2py_version}, vrd)
1187
funcwrappers = []
1188
funcwrappers2 = [] # F90 codes
1189
for n in m['interfaced']:
1190
nb = None
1191
for bi in m['body']:
1192
if bi['block'] not in ['interface', 'abstract interface']:
1193
errmess('buildmodule: Expected interface block. Skipping.\n')
1194
continue
1195
for b in bi['body']:
1196
if b['name'] == n:
1197
nb = b
1198
break
1199
1200
if not nb:
1201
errmess(
1202
'buildmodule: Could not found the body of interfaced routine "%s". Skipping.\n' % (n))
1203
continue
1204
nb_list = [nb]
1205
if 'entry' in nb:
1206
for k, a in nb['entry'].items():
1207
nb1 = copy.deepcopy(nb)
1208
del nb1['entry']
1209
nb1['name'] = k
1210
nb1['args'] = a
1211
nb_list.append(nb1)
1212
for nb in nb_list:
1213
# requiresf90wrapper must be called before buildapi as it
1214
# rewrites assumed shape arrays as automatic arrays.
1215
isf90 = requiresf90wrapper(nb)
1216
api, wrap = buildapi(nb)
1217
if wrap:
1218
if isf90:
1219
funcwrappers2.append(wrap)
1220
else:
1221
funcwrappers.append(wrap)
1222
ar = applyrules(api, vrd)
1223
rd = dictappend(rd, ar)
1224
1225
# Construct COMMON block support
1226
cr, wrap = common_rules.buildhooks(m)
1227
if wrap:
1228
funcwrappers.append(wrap)
1229
ar = applyrules(cr, vrd)
1230
rd = dictappend(rd, ar)
1231
1232
# Construct F90 module support
1233
mr, wrap = f90mod_rules.buildhooks(m)
1234
if wrap:
1235
funcwrappers2.append(wrap)
1236
ar = applyrules(mr, vrd)
1237
rd = dictappend(rd, ar)
1238
1239
for u in um:
1240
ar = use_rules.buildusevars(u, m['use'][u['name']])
1241
rd = dictappend(rd, ar)
1242
1243
needs = cfuncs.get_needs()
1244
code = {}
1245
for n in needs.keys():
1246
code[n] = []
1247
for k in needs[n]:
1248
c = ''
1249
if k in cfuncs.includes0:
1250
c = cfuncs.includes0[k]
1251
elif k in cfuncs.includes:
1252
c = cfuncs.includes[k]
1253
elif k in cfuncs.userincludes:
1254
c = cfuncs.userincludes[k]
1255
elif k in cfuncs.typedefs:
1256
c = cfuncs.typedefs[k]
1257
elif k in cfuncs.typedefs_generated:
1258
c = cfuncs.typedefs_generated[k]
1259
elif k in cfuncs.cppmacros:
1260
c = cfuncs.cppmacros[k]
1261
elif k in cfuncs.cfuncs:
1262
c = cfuncs.cfuncs[k]
1263
elif k in cfuncs.callbacks:
1264
c = cfuncs.callbacks[k]
1265
elif k in cfuncs.f90modhooks:
1266
c = cfuncs.f90modhooks[k]
1267
elif k in cfuncs.commonhooks:
1268
c = cfuncs.commonhooks[k]
1269
else:
1270
errmess('buildmodule: unknown need %s.\n' % (repr(k)))
1271
continue
1272
code[n].append(c)
1273
mod_rules.append(code)
1274
for r in mod_rules:
1275
if ('_check' in r and r['_check'](m)) or ('_check' not in r):
1276
ar = applyrules(r, vrd, m)
1277
rd = dictappend(rd, ar)
1278
ar = applyrules(module_rules, rd)
1279
1280
fn = os.path.join(options['buildpath'], vrd['coutput'])
1281
ret['csrc'] = fn
1282
with open(fn, 'w') as f:
1283
f.write(ar['modulebody'].replace('\t', 2 * ' '))
1284
outmess(' Wrote C/API module "%s" to file "%s"\n' % (m['name'], fn))
1285
1286
if options['dorestdoc']:
1287
fn = os.path.join(
1288
options['buildpath'], vrd['modulename'] + 'module.rest')
1289
with open(fn, 'w') as f:
1290
f.write('.. -*- rest -*-\n')
1291
f.write('\n'.join(ar['restdoc']))
1292
outmess(' ReST Documentation is saved to file "%s/%smodule.rest"\n' %
1293
(options['buildpath'], vrd['modulename']))
1294
if options['dolatexdoc']:
1295
fn = os.path.join(
1296
options['buildpath'], vrd['modulename'] + 'module.tex')
1297
ret['ltx'] = fn
1298
with open(fn, 'w') as f:
1299
f.write(
1300
'%% This file is auto-generated with f2py (version:%s)\n' % (f2py_version))
1301
if 'shortlatex' not in options:
1302
f.write(
1303
'\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n')
1304
f.write('\n'.join(ar['latexdoc']))
1305
if 'shortlatex' not in options:
1306
f.write('\\end{document}')
1307
outmess(' Documentation is saved to file "%s/%smodule.tex"\n' %
1308
(options['buildpath'], vrd['modulename']))
1309
if funcwrappers:
1310
wn = os.path.join(options['buildpath'], vrd['f2py_wrapper_output'])
1311
ret['fsrc'] = wn
1312
with open(wn, 'w') as f:
1313
f.write('C -*- fortran -*-\n')
1314
f.write(
1315
'C This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
1316
f.write(
1317
'C It contains Fortran 77 wrappers to fortran functions.\n')
1318
lines = []
1319
for l in ('\n\n'.join(funcwrappers) + '\n').split('\n'):
1320
if 0 <= l.find('!') < 66:
1321
# don't split comment lines
1322
lines.append(l + '\n')
1323
elif l and l[0] == ' ':
1324
while len(l) >= 66:
1325
lines.append(l[:66] + '\n &')
1326
l = l[66:]
1327
lines.append(l + '\n')
1328
else:
1329
lines.append(l + '\n')
1330
lines = ''.join(lines).replace('\n &\n', '\n')
1331
f.write(lines)
1332
outmess(' Fortran 77 wrappers are saved to "%s"\n' % (wn))
1333
if funcwrappers2:
1334
wn = os.path.join(
1335
options['buildpath'], '%s-f2pywrappers2.f90' % (vrd['modulename']))
1336
ret['fsrc'] = wn
1337
with open(wn, 'w') as f:
1338
f.write('! -*- f90 -*-\n')
1339
f.write(
1340
'! This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
1341
f.write(
1342
'! It contains Fortran 90 wrappers to fortran functions.\n')
1343
lines = []
1344
for l in ('\n\n'.join(funcwrappers2) + '\n').split('\n'):
1345
if 0 <= l.find('!') < 72:
1346
# don't split comment lines
1347
lines.append(l + '\n')
1348
elif len(l) > 72 and l[0] == ' ':
1349
lines.append(l[:72] + '&\n &')
1350
l = l[72:]
1351
while len(l) > 66:
1352
lines.append(l[:66] + '&\n &')
1353
l = l[66:]
1354
lines.append(l + '\n')
1355
else:
1356
lines.append(l + '\n')
1357
lines = ''.join(lines).replace('\n &\n', '\n')
1358
f.write(lines)
1359
outmess(' Fortran 90 wrappers are saved to "%s"\n' % (wn))
1360
return ret
1361
1362
################## Build C/API function #############
1363
1364
stnd = {1: 'st', 2: 'nd', 3: 'rd', 4: 'th', 5: 'th',
1365
6: 'th', 7: 'th', 8: 'th', 9: 'th', 0: 'th'}
1366
1367
1368
def buildapi(rout):
1369
rout, wrap = func2subr.assubr(rout)
1370
args, depargs = getargs2(rout)
1371
capi_maps.depargs = depargs
1372
var = rout['vars']
1373
1374
if ismoduleroutine(rout):
1375
outmess(' Constructing wrapper function "%s.%s"...\n' %
1376
(rout['modulename'], rout['name']))
1377
else:
1378
outmess(' Constructing wrapper function "%s"...\n' % (rout['name']))
1379
# Routine
1380
vrd = capi_maps.routsign2map(rout)
1381
rd = dictappend({}, vrd)
1382
for r in rout_rules:
1383
if ('_check' in r and r['_check'](rout)) or ('_check' not in r):
1384
ar = applyrules(r, vrd, rout)
1385
rd = dictappend(rd, ar)
1386
1387
# Args
1388
nth, nthk = 0, 0
1389
savevrd = {}
1390
for a in args:
1391
vrd = capi_maps.sign2map(a, var[a])
1392
if isintent_aux(var[a]):
1393
_rules = aux_rules
1394
else:
1395
_rules = arg_rules
1396
if not isintent_hide(var[a]):
1397
if not isoptional(var[a]):
1398
nth = nth + 1
1399
vrd['nth'] = repr(nth) + stnd[nth % 10] + ' argument'
1400
else:
1401
nthk = nthk + 1
1402
vrd['nth'] = repr(nthk) + stnd[nthk % 10] + ' keyword'
1403
else:
1404
vrd['nth'] = 'hidden'
1405
savevrd[a] = vrd
1406
for r in _rules:
1407
if '_depend' in r:
1408
continue
1409
if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):
1410
ar = applyrules(r, vrd, var[a])
1411
rd = dictappend(rd, ar)
1412
if '_break' in r:
1413
break
1414
for a in depargs:
1415
if isintent_aux(var[a]):
1416
_rules = aux_rules
1417
else:
1418
_rules = arg_rules
1419
vrd = savevrd[a]
1420
for r in _rules:
1421
if '_depend' not in r:
1422
continue
1423
if ('_check' in r and r['_check'](var[a])) or ('_check' not in r):
1424
ar = applyrules(r, vrd, var[a])
1425
rd = dictappend(rd, ar)
1426
if '_break' in r:
1427
break
1428
if 'check' in var[a]:
1429
for c in var[a]['check']:
1430
vrd['check'] = c
1431
ar = applyrules(check_rules, vrd, var[a])
1432
rd = dictappend(rd, ar)
1433
if isinstance(rd['cleanupfrompyobj'], list):
1434
rd['cleanupfrompyobj'].reverse()
1435
if isinstance(rd['closepyobjfrom'], list):
1436
rd['closepyobjfrom'].reverse()
1437
rd['docsignature'] = stripcomma(replace('#docsign##docsignopt##docsignxa#',
1438
{'docsign': rd['docsign'],
1439
'docsignopt': rd['docsignopt'],
1440
'docsignxa': rd['docsignxa']}))
1441
optargs = stripcomma(replace('#docsignopt##docsignxa#',
1442
{'docsignxa': rd['docsignxashort'],
1443
'docsignopt': rd['docsignoptshort']}
1444
))
1445
if optargs == '':
1446
rd['docsignatureshort'] = stripcomma(
1447
replace('#docsign#', {'docsign': rd['docsign']}))
1448
else:
1449
rd['docsignatureshort'] = replace('#docsign#[#docsignopt#]',
1450
{'docsign': rd['docsign'],
1451
'docsignopt': optargs,
1452
})
1453
rd['latexdocsignatureshort'] = rd['docsignatureshort'].replace('_', '\\_')
1454
rd['latexdocsignatureshort'] = rd[
1455
'latexdocsignatureshort'].replace(',', ', ')
1456
cfs = stripcomma(replace('#callfortran##callfortranappend#', {
1457
'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']}))
1458
if len(rd['callfortranappend']) > 1:
1459
rd['callcompaqfortran'] = stripcomma(replace('#callfortran# 0,#callfortranappend#', {
1460
'callfortran': rd['callfortran'], 'callfortranappend': rd['callfortranappend']}))
1461
else:
1462
rd['callcompaqfortran'] = cfs
1463
rd['callfortran'] = cfs
1464
if isinstance(rd['docreturn'], list):
1465
rd['docreturn'] = stripcomma(
1466
replace('#docreturn#', {'docreturn': rd['docreturn']})) + ' = '
1467
rd['docstrsigns'] = []
1468
rd['latexdocstrsigns'] = []
1469
for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']:
1470
if k in rd and isinstance(rd[k], list):
1471
rd['docstrsigns'] = rd['docstrsigns'] + rd[k]
1472
k = 'latex' + k
1473
if k in rd and isinstance(rd[k], list):
1474
rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\
1475
['\\begin{description}'] + rd[k][1:] +\
1476
['\\end{description}']
1477
1478
ar = applyrules(routine_rules, rd)
1479
if ismoduleroutine(rout):
1480
outmess(' %s\n' % (ar['docshort']))
1481
else:
1482
outmess(' %s\n' % (ar['docshort']))
1483
return ar, wrap
1484
1485
1486
#################### EOF rules.py #######################
1487
1488