Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes15kdownloads
rules.py1630 linesDownload Raw Back to f2py
1"""
2
3Rules for building C/API module with f2py2e.
4
5Here is a skeleton of a new wrapper function (13Dec2001):
6
7wrapper_function(args)
8  declarations
9  get_python_arguments, say, `a' and `b'
10
11  get_a_from_python
12  if (successful) {
13
14    get_b_from_python
15    if (successful) {
16
17      callfortran
18      if (successful) {
19
20        put_a_to_python
21        if (successful) {
22
23          put_b_to_python
24          if (successful) {
25
26            buildvalue = ...
27
28          }
29
30        }
31
32      }
33
34    }
35    cleanup_b
36
37  }
38  cleanup_a
39
40  return buildvalue
41
42Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
43Copyright 2011 -- present NumPy Developers.
44Permission to use, modify, and distribute this software is given under the
45terms of the NumPy License.
46
47NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
48"""
49import copy
50import os
51import sys
52import time
53from pathlib import Path
54
55# __version__.version is now the same as the NumPy version
56from . import (
57    __version__,
58    capi_maps,
59    cfuncs,
60    common_rules,
61    f90mod_rules,
62    func2subr,
63    use_rules,
64)
65from .auxfuncs import (
66    applyrules,
67    debugcapi,
68    dictappend,
69    errmess,
70    gentitle,
71    getargs2,
72    hascallstatement,
73    hasexternals,
74    hasinitvalue,
75    hasnote,
76    hasresultnote,
77    isarray,
78    isarrayofstrings,
79    isattr_value,
80    ischaracter,
81    ischaracter_or_characterarray,
82    ischaracterarray,
83    iscomplex,
84    iscomplexarray,
85    iscomplexfunction,
86    iscomplexfunction_warn,
87    isdummyroutine,
88    isexternal,
89    isfunction,
90    isfunction_wrap,
91    isint1,
92    isint1array,
93    isintent_aux,
94    isintent_c,
95    isintent_callback,
96    isintent_copy,
97    isintent_hide,
98    isintent_inout,
99    isintent_nothide,
100    isintent_out,
101    isintent_overwrite,
102    islogical,
103    islong_complex,
104    islong_double,
105    islong_doublefunction,
106    islong_long,
107    islong_longfunction,
108    ismoduleroutine,
109    isoptional,
110    isrequired,
111    isscalar,
112    issigned_long_longarray,
113    isstring,
114    isstringarray,
115    isstringfunction,
116    issubroutine,
117    issubroutine_wrap,
118    isthreadsafe,
119    isunsigned,
120    isunsigned_char,
121    isunsigned_chararray,
122    isunsigned_long_long,
123    isunsigned_long_longarray,
124    isunsigned_short,
125    isunsigned_shortarray,
126    l_and,
127    l_not,
128    l_or,
129    outmess,
130    replace,
131    requiresf90wrapper,
132    stripcomma,
133)
134
135f2py_version = __version__.version
136numpy_version = __version__.version
137
138options = {}
139sepdict = {}
140# for k in ['need_cfuncs']: sepdict[k]=','
141for k in ['decl',
142          'frompyobj',
143          'cleanupfrompyobj',
144          'topyarr', 'method',
145          'pyobjfrom', 'closepyobjfrom',
146          'freemem',
147          'userincludes',
148          'includes0', 'includes', 'typedefs', 'typedefs_generated',
149          'cppmacros', 'cfuncs', 'callbacks',
150          'latexdoc',
151          'restdoc',
152          'routine_defs', 'externroutines',
153          'initf2pywraphooks',
154          'commonhooks', 'initcommonhooks',
155          'f90modhooks', 'initf90modhooks']:
156    sepdict[k] = '\n'
157
158#################### Rules for C/API module #################
159
160generationtime = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
161module_rules = {
162    'modulebody': """\
163/* File: #modulename#module.c
164 * This file is auto-generated with f2py (version:#f2py_version#).
165 * f2py is a Fortran to Python Interface Generator (FPIG), Second Edition,
166 * written by Pearu Peterson <pearu@cens.ioc.ee>.
167 * Generation date: """ + time.asctime(time.gmtime(generationtime)) + """
168 * Do not edit this file directly unless you know what you are doing!!!
169 */
170
171#ifdef __cplusplus
172extern \"C\" {
173#endif
174
175#ifndef PY_SSIZE_T_CLEAN
176#define PY_SSIZE_T_CLEAN
177#endif /* PY_SSIZE_T_CLEAN */
178
179/* Unconditionally included */
180#include <Python.h>
181#include <numpy/npy_os.h>
182
183""" + gentitle("See f2py2e/cfuncs.py: includes") + """
184#includes#
185#includes0#
186
187""" + gentitle("See f2py2e/rules.py: mod_rules['modulebody']") + """
188static PyObject *#modulename#_error;
189static PyObject *#modulename#_module;
190
191""" + gentitle("See f2py2e/cfuncs.py: typedefs") + """
192#typedefs#
193
194""" + gentitle("See f2py2e/cfuncs.py: typedefs_generated") + """
195#typedefs_generated#
196
197""" + gentitle("See f2py2e/cfuncs.py: cppmacros") + """
198#cppmacros#
199
200""" + gentitle("See f2py2e/cfuncs.py: cfuncs") + """
201#cfuncs#
202
203""" + gentitle("See f2py2e/cfuncs.py: userincludes") + """
204#userincludes#
205
206""" + gentitle("See f2py2e/capi_rules.py: usercode") + """
207#usercode#
208
209/* See f2py2e/rules.py */
210#externroutines#
211
212""" + gentitle("See f2py2e/capi_rules.py: usercode1") + """
213#usercode1#
214
215""" + gentitle("See f2py2e/cb_rules.py: buildcallback") + """
216#callbacks#
217
218""" + gentitle("See f2py2e/rules.py: buildapi") + """
219#body#
220
221""" + gentitle("See f2py2e/f90mod_rules.py: buildhooks") + """
222#f90modhooks#
223
224""" + gentitle("See f2py2e/rules.py: module_rules['modulebody']") + """
225
226""" + gentitle("See f2py2e/common_rules.py: buildhooks") + """
227#commonhooks#
228
229""" + gentitle("See f2py2e/rules.py") + """
230
231static FortranDataDef f2py_routine_defs[] = {
232#routine_defs#
233    {NULL}
234};
235
236static PyMethodDef f2py_module_methods[] = {
237#pymethoddef#
238    {NULL,NULL}
239};
240
241static struct PyModuleDef moduledef = {
242    PyModuleDef_HEAD_INIT,
243    "#modulename#",
244    NULL,
245    -1,
246    f2py_module_methods,
247    NULL,
248    NULL,
249    NULL,
250    NULL
251};
252
253PyMODINIT_FUNC PyInit_#modulename#(void) {
254    int i;
255    PyObject *m,*d, *s, *tmp;
256    m = #modulename#_module = PyModule_Create(&moduledef);
257    Py_SET_TYPE(&PyFortran_Type, &PyType_Type);
258    import_array();
259    if (PyErr_Occurred())
260        {PyErr_SetString(PyExc_ImportError, \"can't initialize module #modulename# (failed to import numpy)\"); return m;}
261    d = PyModule_GetDict(m);
262    s = PyUnicode_FromString(\"#f2py_version#\");
263    PyDict_SetItemString(d, \"__version__\", s);
264    Py_DECREF(s);
265    s = PyUnicode_FromString(
266        \"This module '#modulename#' is auto-generated with f2py (version:#f2py_version#).\\nFunctions:\\n\"\n#docs#\".\");
267    PyDict_SetItemString(d, \"__doc__\", s);
268    Py_DECREF(s);
269    s = PyUnicode_FromString(\"""" + numpy_version + """\");
270    PyDict_SetItemString(d, \"__f2py_numpy_version__\", s);
271    Py_DECREF(s);
272    #modulename#_error = PyErr_NewException (\"#modulename#.error\", NULL, NULL);
273    /*
274     * Store the error object inside the dict, so that it could get deallocated.
275     * (in practice, this is a module, so it likely will not and cannot.)
276     */
277    PyDict_SetItemString(d, \"_#modulename#_error\", #modulename#_error);
278    Py_DECREF(#modulename#_error);
279    for(i=0;f2py_routine_defs[i].name!=NULL;i++) {
280        tmp = PyFortranObject_NewAsAttr(&f2py_routine_defs[i]);
281        PyDict_SetItemString(d, f2py_routine_defs[i].name, tmp);
282        Py_DECREF(tmp);
283    }
284#initf2pywraphooks#
285#initf90modhooks#
286#initcommonhooks#
287#interface_usercode#
288
289#ifdef Py_GIL_DISABLED
290    // signal whether this module supports running with the GIL disabled
291    PyUnstable_Module_SetGIL(m , #gil_used#);
292#endif
293
294#ifdef F2PY_REPORT_ATEXIT
295    if (! PyErr_Occurred())
296        on_exit(f2py_report_on_exit,(void*)\"#modulename#\");
297#endif
298
299    if (PyType_Ready(&PyFortran_Type) < 0) {
300        return NULL;
301    }
302
303    return m;
304}
305#ifdef __cplusplus
306}
307#endif
308""",
309    'separatorsfor': {'latexdoc': '\n\n',
310                      'restdoc': '\n\n'},
311    'latexdoc': ['\\section{Module \\texttt{#texmodulename#}}\n',
312                 '#modnote#\n',
313                 '#latexdoc#'],
314    'restdoc': ['Module #modulename#\n' + '=' * 80,
315                '\n#restdoc#']
316}
317
318defmod_rules = [
319    {'body': '/*eof body*/',
320     'method': '/*eof method*/',
321     'externroutines': '/*eof externroutines*/',
322     'routine_defs': '/*eof routine_defs*/',
323     'initf90modhooks': '/*eof initf90modhooks*/',
324     'initf2pywraphooks': '/*eof initf2pywraphooks*/',
325     'initcommonhooks': '/*eof initcommonhooks*/',
326     'latexdoc': '',
327     'restdoc': '',
328     'modnote': {hasnote: '#note#', l_not(hasnote): ''},
329     }
330]
331
332routine_rules = {
333    'separatorsfor': sepdict,
334    'body': """
335#begintitle#
336static char doc_#apiname#[] = \"\\\n#docreturn##name#(#docsignatureshort#)\\n\\nWrapper for ``#name#``.\\\n\\n#docstrsigns#\";
337/* #declfortranroutine# */
338static PyObject *#apiname#(const PyObject *capi_self,
339                           PyObject *capi_args,
340                           PyObject *capi_keywds,
341                           #functype# (*f2py_func)(#callprotoargument#)) {
342    PyObject * volatile capi_buildvalue = NULL;
343    volatile int f2py_success = 1;
344#decl#
345    static char *capi_kwlist[] = {#kwlist##kwlistopt##kwlistxa#NULL};
346#usercode#
347#routdebugenter#
348#ifdef F2PY_REPORT_ATEXIT
349f2py_start_clock();
350#endif
351    if (!PyArg_ParseTupleAndKeywords(capi_args,capi_keywds,\\
352        \"#argformat#|#keyformat##xaformat#:#pyname#\",\\
353        capi_kwlist#args_capi##keys_capi##keys_xa#))\n        return NULL;
354#frompyobj#
355/*end of frompyobj*/
356#ifdef F2PY_REPORT_ATEXIT
357f2py_start_call_clock();
358#endif
359#callfortranroutine#
360if (PyErr_Occurred())
361  f2py_success = 0;
362#ifdef F2PY_REPORT_ATEXIT
363f2py_stop_call_clock();
364#endif
365/*end of callfortranroutine*/
366        if (f2py_success) {
367#pyobjfrom#
368/*end of pyobjfrom*/
369        CFUNCSMESS(\"Building return value.\\n\");
370        capi_buildvalue = Py_BuildValue(\"#returnformat#\"#return#);
371/*closepyobjfrom*/
372#closepyobjfrom#
373        } /*if (f2py_success) after callfortranroutine*/
374/*cleanupfrompyobj*/
375#cleanupfrompyobj#
376    if (capi_buildvalue == NULL) {
377#routdebugfailure#
378    } else {
379#routdebugleave#
380    }
381    CFUNCSMESS(\"Freeing memory.\\n\");
382#freemem#
383#ifdef F2PY_REPORT_ATEXIT
384f2py_stop_clock();
385#endif
386    return capi_buildvalue;
387}
388#endtitle#
389""",
390    'routine_defs': '#routine_def#',
391    'initf2pywraphooks': '#initf2pywraphook#',
392    'externroutines': '#declfortranroutine#',
393    'doc': '#docreturn##name#(#docsignature#)',
394    'docshort': '#docreturn##name#(#docsignatureshort#)',
395    'docs': '"    #docreturn##name#(#docsignature#)\\n"\n',
396    'need': ['arrayobject.h', 'CFUNCSMESS', 'MINMAX'],
397    'cppmacros': {debugcapi: '#define DEBUGCFUNCS'},
398    'latexdoc': ['\\subsection{Wrapper function \\texttt{#texname#}}\n',
399                 """
400\\noindent{{}\\verb@#docreturn##name#@{}}\\texttt{(#latexdocsignatureshort#)}
401#routnote#
402
403#latexdocstrsigns#
404"""],
405    'restdoc': ['Wrapped function ``#name#``\n' + '-' * 80,
406
407                ]
408}
409
410################## Rules for C/API function ##############
411
412rout_rules = [
413    {  # Init
414        'separatorsfor': {'callfortranroutine': '\n', 'routdebugenter': '\n', 'decl': '\n',
415                          'routdebugleave': '\n', 'routdebugfailure': '\n',
416                          'setjmpbuf': ' || ',
417                          'docstrreq': '\n', 'docstropt': '\n', 'docstrout': '\n',
418                          'docstrcbs': '\n', 'docstrsigns': '\\n"\n"',
419                          'latexdocstrsigns': '\n',
420                          'latexdocstrreq': '\n', 'latexdocstropt': '\n',
421                          'latexdocstrout': '\n', 'latexdocstrcbs': '\n',
422                          },
423        'kwlist': '', 'kwlistopt': '', 'callfortran': '', 'callfortranappend': '',
424        'docsign': '', 'docsignopt': '', 'decl': '/*decl*/',
425        'freemem': '/*freemem*/',
426        'docsignshort': '', 'docsignoptshort': '',
427        'docstrsigns': '', 'latexdocstrsigns': '',
428        'docstrreq': '\\nParameters\\n----------',
429        'docstropt': '\\nOther Parameters\\n----------------',
430        'docstrout': '\\nReturns\\n-------',
431        'docstrcbs': '\\nNotes\\n-----\\nCall-back functions::\\n',
432        'latexdocstrreq': '\\noindent Required arguments:',
433        'latexdocstropt': '\\noindent Optional arguments:',
434        'latexdocstrout': '\\noindent Return objects:',
435        'latexdocstrcbs': '\\noindent Call-back functions:',
436        'args_capi': '', 'keys_capi': '', 'functype': '',
437        'frompyobj': '/*frompyobj*/',
438        # this list will be reversed
439        'cleanupfrompyobj': ['/*end of cleanupfrompyobj*/'],
440        'pyobjfrom': '/*pyobjfrom*/',
441        # this list will be reversed
442        'closepyobjfrom': ['/*end of closepyobjfrom*/'],
443        'topyarr': '/*topyarr*/', 'routdebugleave': '/*routdebugleave*/',
444        'routdebugenter': '/*routdebugenter*/',
445        'routdebugfailure': '/*routdebugfailure*/',
446        'callfortranroutine': '/*callfortranroutine*/',
447        'argformat': '', 'keyformat': '', 'need_cfuncs': '',
448        'docreturn': '', 'return': '', 'returnformat': '', 'rformat': '',
449        'kwlistxa': '', 'keys_xa': '', 'xaformat': '', 'docsignxa': '', 'docsignxashort': '',
450        'initf2pywraphook': '',
451        'routnote': {hasnote: '--- #note#', l_not(hasnote): ''},
452    }, {
453        'apiname': 'f2py_rout_#modulename#_#name#',
454        'pyname': '#modulename#.#name#',
455        'decl': '',
456        '_check': l_not(ismoduleroutine)
457    }, {
458        'apiname': 'f2py_rout_#modulename#_#f90modulename#_#name#',
459        'pyname': '#modulename#.#f90modulename#.#name#',
460        'decl': '',
461        '_check': ismoduleroutine
462    }, {  # Subroutine
463        'functype': 'void',
464        'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
465                               l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern void #fortranname#(#callprotoargument#);',
466                               ismoduleroutine: '',
467                               isdummyroutine: ''
468                               },
469        'routine_def': {
470            l_not(l_or(ismoduleroutine, isintent_c, isdummyroutine)):
471            '    {\"#name#\",-1,{{-1}},0,0,(char *)'
472            '  #F_FUNC#(#fortranname#,#FORTRANNAME#),'
473            '  (f2py_init_func)#apiname#,doc_#apiname#},',
474            l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):
475            '    {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,'
476            '  (f2py_init_func)#apiname#,doc_#apiname#},',
477            l_and(l_not(ismoduleroutine), isdummyroutine):
478            '    {\"#name#\",-1,{{-1}},0,0,NULL,'
479            '  (f2py_init_func)#apiname#,doc_#apiname#},',
480        },
481        'need': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'F_FUNC'},
482        'callfortranroutine': [
483            {debugcapi: [
484                """    fprintf(stderr,\"debug-capi:Fortran subroutine `#fortranname#(#callfortran#)\'\\n\");"""]},
485            {hasexternals: """\
486        if (#setjmpbuf#) {
487            f2py_success = 0;
488        } else {"""},
489            {isthreadsafe: '            Py_BEGIN_ALLOW_THREADS'},
490            {hascallstatement: '''                #callstatement#;
491                /*(*f2py_func)(#callfortran#);*/'''},
492            {l_not(l_or(hascallstatement, isdummyroutine))
493                   : '                (*f2py_func)(#callfortran#);'},
494            {isthreadsafe: '            Py_END_ALLOW_THREADS'},
495            {hasexternals: """        }"""}
496        ],
497        '_check': l_and(issubroutine, l_not(issubroutine_wrap)),
498    }, {  # Wrapped function
499        'functype': 'void',
500        'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',
501                               isdummyroutine: '',
502                               },
503
504        'routine_def': {
505            l_not(l_or(ismoduleroutine, isdummyroutine)):
506            '    {\"#name#\",-1,{{-1}},0,0,(char *)'
507            '  #F_WRAPPEDFUNC#(#name_lower#,#NAME#),'
508            '  (f2py_init_func)#apiname#,doc_#apiname#},',
509            isdummyroutine:
510            '    {\"#name#\",-1,{{-1}},0,0,NULL,'
511            '  (f2py_init_func)#apiname#,doc_#apiname#},',
512        },
513        'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '''
514    {
515      extern #ctype# #F_FUNC#(#name_lower#,#NAME#)(void);
516      PyObject* o = PyDict_GetItemString(d,"#name#");
517      tmp = F2PyCapsule_FromVoidPtr((void*)#F_WRAPPEDFUNC#(#name_lower#,#NAME#),NULL);
518      PyObject_SetAttrString(o,"_cpointer", tmp);
519      Py_DECREF(tmp);
520      s = PyUnicode_FromString("#name#");
521      PyObject_SetAttrString(o,"__name__", s);
522      Py_DECREF(s);
523    }
524    '''},
525        'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},
526        'callfortranroutine': [
527            {debugcapi: [
528                """    fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},
529            {hasexternals: """\
530    if (#setjmpbuf#) {
531        f2py_success = 0;
532    } else {"""},
533            {isthreadsafe: '    Py_BEGIN_ALLOW_THREADS'},
534            {l_not(l_or(hascallstatement, isdummyroutine))
535                   : '    (*f2py_func)(#callfortran#);'},
536            {hascallstatement:
537                '    #callstatement#;\n    /*(*f2py_func)(#callfortran#);*/'},
538            {isthreadsafe: '    Py_END_ALLOW_THREADS'},
539            {hasexternals: '    }'}
540        ],
541        '_check': isfunction_wrap,
542    }, {  # Wrapped subroutine
543        'functype': 'void',
544        'declfortranroutine': {l_not(l_or(ismoduleroutine, isdummyroutine)): 'extern void #F_WRAPPEDFUNC#(#name_lower#,#NAME#)(#callprotoargument#);',
545                               isdummyroutine: '',
546                               },
547
548        'routine_def': {
549            l_not(l_or(ismoduleroutine, isdummyroutine)):
550            '    {\"#name#\",-1,{{-1}},0,0,(char *)'
551            '  #F_WRAPPEDFUNC#(#name_lower#,#NAME#),'
552            '  (f2py_init_func)#apiname#,doc_#apiname#},',
553            isdummyroutine:
554            '    {\"#name#\",-1,{{-1}},0,0,NULL,'
555            '  (f2py_init_func)#apiname#,doc_#apiname#},',
556        },
557        'initf2pywraphook': {l_not(l_or(ismoduleroutine, isdummyroutine)): '''
558    {
559      extern void #F_FUNC#(#name_lower#,#NAME#)(void);
560      PyObject* o = PyDict_GetItemString(d,"#name#");
561      tmp = F2PyCapsule_FromVoidPtr((void*)#F_FUNC#(#name_lower#,#NAME#),NULL);
562      PyObject_SetAttrString(o,"_cpointer", tmp);
563      Py_DECREF(tmp);
564      s = PyUnicode_FromString("#name#");
565      PyObject_SetAttrString(o,"__name__", s);
566      Py_DECREF(s);
567    }
568    '''},
569        'need': {l_not(l_or(ismoduleroutine, isdummyroutine)): ['F_WRAPPEDFUNC', 'F_FUNC']},
570        'callfortranroutine': [
571            {debugcapi: [
572                """    fprintf(stderr,\"debug-capi:Fortran subroutine `f2pywrap#name_lower#(#callfortran#)\'\\n\");"""]},
573            {hasexternals: """\
574    if (#setjmpbuf#) {
575        f2py_success = 0;
576    } else {"""},
577            {isthreadsafe: '    Py_BEGIN_ALLOW_THREADS'},
578            {l_not(l_or(hascallstatement, isdummyroutine))
579                   : '    (*f2py_func)(#callfortran#);'},
580            {hascallstatement:
581                '    #callstatement#;\n    /*(*f2py_func)(#callfortran#);*/'},
582            {isthreadsafe: '    Py_END_ALLOW_THREADS'},
583            {hasexternals: '    }'}
584        ],
585        '_check': issubroutine_wrap,
586    }, {  # Function
587        'functype': '#ctype#',
588        'docreturn': {l_not(isintent_hide): '#rname#,'},
589        'docstrout': '#pydocsignout#',
590        'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}',
591                           {hasresultnote: '--- #resultnote#'}],
592        'callfortranroutine': [{l_and(debugcapi, isstringfunction): """\
593#ifdef USESCOMPAQFORTRAN
594    fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callcompaqfortran#)\\n\");
595#else
596    fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\");
597#endif
598"""},
599                               {l_and(debugcapi, l_not(isstringfunction)): """\
600    fprintf(stderr,\"debug-capi:Fortran function #ctype# #fortranname#(#callfortran#)\\n\");
601"""}
602                               ],
603        '_check': l_and(isfunction, l_not(isfunction_wrap))
604    }, {  # Scalar function
605        'declfortranroutine': {l_and(l_not(l_or(ismoduleroutine, isintent_c)), l_not(isdummyroutine)): 'extern #ctype# #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
606                               l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)): 'extern #ctype# #fortranname#(#callprotoargument#);',
607                               isdummyroutine: ''
608                               },
609        'routine_def': {
610            l_and(l_not(l_or(ismoduleroutine, isintent_c)),
611                  l_not(isdummyroutine)):
612            ('    {\"#name#\",-1,{{-1}},0,0,(char *)'
613             '  #F_FUNC#(#fortranname#,#FORTRANNAME#),'
614             '  (f2py_init_func)#apiname#,doc_#apiname#},'),
615            l_and(l_not(ismoduleroutine), isintent_c, l_not(isdummyroutine)):
616            ('    {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,'
617             '  (f2py_init_func)#apiname#,doc_#apiname#},'),
618            isdummyroutine:
619            '    {\"#name#\",-1,{{-1}},0,0,NULL,'
620            '(f2py_init_func)#apiname#,doc_#apiname#},',
621        },
622        'decl': [{iscomplexfunction_warn: '    #ctype# #name#_return_value={0,0};',
623                  l_not(iscomplexfunction): '    #ctype# #name#_return_value=0;'},
624                 {iscomplexfunction:
625                  '    PyObject *#name#_return_value_capi = Py_None;'}
626                 ],
627        'callfortranroutine': [
628            {hasexternals: """\
629    if (#setjmpbuf#) {
630        f2py_success = 0;
631    } else {"""},
632            {isthreadsafe: '    Py_BEGIN_ALLOW_THREADS'},
633            {hascallstatement: '''    #callstatement#;
634/*    #name#_return_value = (*f2py_func)(#callfortran#);*/
635'''},
636            {l_not(l_or(hascallstatement, isdummyroutine))
637                   : '    #name#_return_value = (*f2py_func)(#callfortran#);'},
638            {isthreadsafe: '    Py_END_ALLOW_THREADS'},
639            {hasexternals: '    }'},
640            {l_and(debugcapi, iscomplexfunction)
641                   : '    fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value.r,#name#_return_value.i);'},
642            {l_and(debugcapi, l_not(iscomplexfunction)): '    fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value);'}],
643        'pyobjfrom': {iscomplexfunction: '    #name#_return_value_capi = pyobj_from_#ctype#1(#name#_return_value);'},
644        'need': [{l_not(isdummyroutine): 'F_FUNC'},
645                 {iscomplexfunction: 'pyobj_from_#ctype#1'},
646                 {islong_longfunction: 'long_long'},
647                 {islong_doublefunction: 'long_double'}],
648        'returnformat': {l_not(isintent_hide): '#rformat#'},
649        'return': {iscomplexfunction: ',#name#_return_value_capi',
650                   l_not(l_or(iscomplexfunction, isintent_hide)): ',#name#_return_value'},
651        '_check': l_and(isfunction, l_not(isstringfunction), l_not(isfunction_wrap))
652    }, {  # String function # in use for --no-wrap
653        'declfortranroutine': 'extern void #F_FUNC#(#fortranname#,#FORTRANNAME#)(#callprotoargument#);',
654        'routine_def': {l_not(l_or(ismoduleroutine, isintent_c)):
655                        '    {\"#name#\",-1,{{-1}},0,0,(char *)#F_FUNC#(#fortranname#,#FORTRANNAME#),(f2py_init_func)#apiname#,doc_#apiname#},',
656                        l_and(l_not(ismoduleroutine), isintent_c):
657                        '    {\"#name#\",-1,{{-1}},0,0,(char *)#fortranname#,(f2py_init_func)#apiname#,doc_#apiname#},'
658                        },
659        'decl': ['    #ctype# #name#_return_value = NULL;',
660                 '    int #name#_return_value_len = 0;'],
661        'callfortran': '#name#_return_value,#name#_return_value_len,',
662        'callfortranroutine': ['    #name#_return_value_len = #rlength#;',
663                               '    if ((#name#_return_value = (string)malloc(#name#_return_value_len+1) == NULL) {',
664                               '        PyErr_SetString(PyExc_MemoryError, \"out of memory\");',
665                               '        f2py_success = 0;',
666                               '    } else {',
667                               "        (#name#_return_value)[#name#_return_value_len] = '\\0';",
668                               '    }',
669                               '    if (f2py_success) {',
670                               {hasexternals: """\
671        if (#setjmpbuf#) {
672            f2py_success = 0;
673        } else {"""},
674                               {isthreadsafe: '        Py_BEGIN_ALLOW_THREADS'},
675                              """\
676#ifdef USESCOMPAQFORTRAN
677        (*f2py_func)(#callcompaqfortran#);
678#else
679        (*f2py_func)(#callfortran#);
680#endif
681""",
682                               {isthreadsafe: '        Py_END_ALLOW_THREADS'},
683                               {hasexternals: '        }'},
684                               {debugcapi:
685                                  '        fprintf(stderr,"#routdebugshowvalue#\\n",#name#_return_value_len,#name#_return_value);'},
686                               '    } /* if (f2py_success) after (string)malloc */',
687                              ],
688        'returnformat': '#rformat#',
689        'return': ',#name#_return_value',
690        'freemem': '    STRINGFREE(#name#_return_value);',
691        'need': ['F_FUNC', '#ctype#', 'STRINGFREE'],
692        '_check': l_and(isstringfunction, l_not(isfunction_wrap))  # ???obsolete
693    },
694    {  # Debugging
695        'routdebugenter': '    fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#(#docsignature#)\\n");',
696        'routdebugleave': '    fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: successful.\\n");',
697        'routdebugfailure': '    fprintf(stderr,"debug-capi:Python C/API function #modulename#.#name#: failure.\\n");',
698        '_check': debugcapi
699    }
700]
701
702################ Rules for arguments ##################
703
704typedef_need_dict = {islong_long: 'long_long',
705                     islong_double: 'long_double',
706                     islong_complex: 'complex_long_double',
707                     isunsigned_char: 'unsigned_char',
708                     isunsigned_short: 'unsigned_short',
709                     isunsigned: 'unsigned',
710                     isunsigned_long_long: 'unsigned_long_long',
711                     isunsigned_chararray: 'unsigned_char',
712                     isunsigned_shortarray: 'unsigned_short',
713                     isunsigned_long_longarray: 'unsigned_long_long',
714                     issigned_long_longarray: 'long_long',
715                     isint1: 'signed_char',
716                     ischaracter_or_characterarray: 'character',
717                     }
718
719aux_rules = [
720    {
721        'separatorsfor': sepdict
722    },
723    {  # Common
724        'frompyobj': ['    /* Processing auxiliary variable #varname# */',
725                      {debugcapi: '    fprintf(stderr,"#vardebuginfo#\\n");'}, ],
726        'cleanupfrompyobj': '    /* End of cleaning variable #varname# */',
727        'need': typedef_need_dict,
728    },
729    # Scalars (not complex)
730    {  # Common
731        'decl': '    #ctype# #varname# = 0;',
732        'need': {hasinitvalue: 'math.h'},
733        'frompyobj': {hasinitvalue: '    #varname# = #init#;'},
734        '_check': l_and(isscalar, l_not(iscomplex)),
735    },
736    {
737        'return': ',#varname#',
738        'docstrout': '#pydocsignout#',
739        'docreturn': '#outvarname#,',
740        'returnformat': '#varrformat#',
741        '_check': l_and(isscalar, l_not(iscomplex), isintent_out),
742    },
743    # Complex scalars
744    {  # Common
745        'decl': '    #ctype# #varname#;',
746        'frompyobj': {hasinitvalue: '    #varname#.r = #init.r#, #varname#.i = #init.i#;'},
747        '_check': iscomplex
748    },
749    # String
750    {  # Common
751        'decl': ['    #ctype# #varname# = NULL;',
752                 '    int slen(#varname#);',
753                 ],
754        'need': ['len..'],
755        '_check': isstring
756    },
757    # Array
758    {  # Common
759        'decl': ['    #ctype# *#varname# = NULL;',
760                 '    npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',
761                 '    const int #varname#_Rank = #rank#;',
762                 ],
763        'need': ['len..', {hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],
764        '_check': isarray
765    },
766    # Scalararray
767    {  # Common
768        '_check': l_and(isarray, l_not(iscomplexarray))
769    }, {  # Not hidden
770        '_check': l_and(isarray, l_not(iscomplexarray), isintent_nothide)
771    },
772    # Integer*1 array
773    {'need': '#ctype#',
774     '_check': isint1array,
775     '_depend': ''
776     },
777    # Integer*-1 array
778    {'need': '#ctype#',
779     '_check': l_or(isunsigned_chararray, isunsigned_char),
780     '_depend': ''
781     },
782    # Integer*-2 array
783    {'need': '#ctype#',
784     '_check': isunsigned_shortarray,
785     '_depend': ''
786     },
787    # Integer*-8 array
788    {'need': '#ctype#',
789     '_check': isunsigned_long_longarray,
790     '_depend': ''
791     },
792    # Complexarray
793    {'need': '#ctype#',
794     '_check': iscomplexarray,
795     '_depend': ''
796     },
797    # Stringarray
798    {
799        'callfortranappend': {isarrayofstrings: 'flen(#varname#),'},
800        'need': 'string',
801        '_check': isstringarray
802    }
803]
804
805arg_rules = [
806    {
807        'separatorsfor': sepdict
808    },
809    {  # Common
810        'frompyobj': ['    /* Processing variable #varname# */',
811                      {debugcapi: '    fprintf(stderr,"#vardebuginfo#\\n");'}, ],
812        'cleanupfrompyobj': '    /* End of cleaning variable #varname# */',
813        '_depend': '',
814        'need': typedef_need_dict,
815    },
816    # Doc signatures
817    {
818        'docstropt': {l_and(isoptional, isintent_nothide): '#pydocsign#'},
819        'docstrreq': {l_and(isrequired, isintent_nothide): '#pydocsign#'},
820        'docstrout': {isintent_out: '#pydocsignout#'},
821        'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
822                                                                 {hasnote: '--- #note#'}]},
823        'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}',
824                                                                 {hasnote: '--- #note#'}]},
825        'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}',
826                                          {l_and(hasnote, isintent_hide): '--- #note#',
827                                           l_and(hasnote, isintent_nothide): '--- See above.'}]},
828        'depend': ''
829    },
830    # Required/Optional arguments
831    {
832        'kwlist': '"#varname#",',
833        'docsign': '#varname#,',
834        '_check': l_and(isintent_nothide, l_not(isoptional))
835    },
836    {
837        'kwlistopt': '"#varname#",',
838        'docsignopt': '#varname#=#showinit#,',
839        'docsignoptshort': '#varname#,',
840        '_check': l_and(isintent_nothide, isoptional)
841    },
842    # Docstring/BuildValue
843    {
844        'docreturn': '#outvarname#,',
845        'returnformat': '#varrformat#',
846        '_check': isintent_out
847    },
848    # Externals (call-back functions)
849    {  # Common
850        'docsignxa': {isintent_nothide: '#varname#_extra_args=(),'},
851        'docsignxashort': {isintent_nothide: '#varname#_extra_args,'},
852        'docstropt': {isintent_nothide: '#varname#_extra_args : input tuple, optional\\n    Default: ()'},
853        'docstrcbs': '#cbdocstr#',
854        'latexdocstrcbs': '\\item[] #cblatexdocstr#',
855        'latexdocstropt': {isintent_nothide: '\\item[]{{}\\verb@#varname#_extra_args := () input tuple@{}} --- Extra arguments for call-back function {{}\\verb@#varname#@{}}.'},
856        'decl': ['    #cbname#_t #varname#_cb = { Py_None, NULL, 0 };',
857                 '    #cbname#_t *#varname#_cb_ptr = &#varname#_cb;',
858                 '    PyTupleObject *#varname#_xa_capi = NULL;',
859                 {l_not(isintent_callback):
860                  '    #cbname#_typedef #varname#_cptr;'}
861                 ],
862        'kwlistxa': {isintent_nothide: '"#varname#_extra_args",'},
863        'argformat': {isrequired: 'O'},
864        'keyformat': {isoptional: 'O'},
865        'xaformat': {isintent_nothide: 'O!'},
866        'args_capi': {isrequired: ',&#varname#_cb.capi'},
867        'keys_capi': {isoptional: ',&#varname#_cb.capi'},
868        'keys_xa': ',&PyTuple_Type,&#varname#_xa_capi',
869        'setjmpbuf': '(setjmp(#varname#_cb.jmpbuf))',
870        'callfortran': {l_not(isintent_callback): '#varname#_cptr,'},
871        'need': ['#cbname#', 'setjmp.h'],
872        '_check': isexternal
873    },
874    {
875        'frompyobj': [{l_not(isintent_callback): """\
876if(F2PyCapsule_Check(#varname#_cb.capi)) {
877  #varname#_cptr = F2PyCapsule_AsVoidPtr(#varname#_cb.capi);
878} else {
879  #varname#_cptr = #cbname#;
880}
881"""}, {isintent_callback: """\
882if (#varname#_cb.capi==Py_None) {
883  #varname#_cb.capi = PyObject_GetAttrString(#modulename#_module,\"#varname#\");
884  if (#varname#_cb.capi) {
885    if (#varname#_xa_capi==NULL) {
886      if (PyObject_HasAttrString(#modulename#_module,\"#varname#_extra_args\")) {
887        PyObject* capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#varname#_extra_args\");
888        if (capi_tmp) {
889          #varname#_xa_capi = (PyTupleObject *)PySequence_Tuple(capi_tmp);
890          Py_DECREF(capi_tmp);
891        }
892        else {
893          #varname#_xa_capi = (PyTupleObject *)Py_BuildValue(\"()\");
894        }
895        if (#varname#_xa_capi==NULL) {
896          PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#varname#_extra_args to tuple.\\n\");
897          return NULL;
898        }
899      }
900    }
901  }
902  if (#varname#_cb.capi==NULL) {
903    PyErr_SetString(#modulename#_error,\"Callback #varname# not defined (as an argument or module #modulename# attribute).\\n\");
904    return NULL;
905  }
906}
907"""},
908            """\
909    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#.\")) {
910""",
911            {debugcapi: ["""\
912        fprintf(stderr,\"debug-capi:Assuming %d arguments; at most #maxnofargs#(-#nofoptargs#) is expected.\\n\",#varname#_cb.nofargs);
913        CFUNCSMESSPY(\"for #varname#=\",#varname#_cb.capi);""",
914                         {l_not(isintent_callback): """        fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]},
915            """\
916        CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\");
917        #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""",
918        ],
919        'cleanupfrompyobj':
920        """\
921        CFUNCSMESS(\"Restoring callback variables for `#varname#`.\\n\");
922        #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);
923        Py_DECREF(#varname#_cb.args_capi);
924    }""",
925        'need': ['SWAP', 'create_cb_arglist'],
926        '_check': isexternal,
927        '_depend': ''
928    },
929    # Scalars (not complex)
930    {  # Common
931        'decl': '    #ctype# #varname# = 0;',
932        'pyobjfrom': {debugcapi: '    fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},
933        'callfortran': {l_or(isintent_c, isattr_value): '#varname#,', l_not(l_or(isintent_c, isattr_value)): '&#varname#,'},
934        'return': {isintent_out: ',#varname#'},
935        '_check': l_and(isscalar, l_not(iscomplex))
936    }, {
937        'need': {hasinitvalue: 'math.h'},
938        '_check': l_and(isscalar, l_not(iscomplex)),
939    }, {  # Not hidden
940        'decl': '    PyObject *#varname#_capi = Py_None;',
941        'argformat': {isrequired: 'O'},
942        'keyformat': {isoptional: 'O'},
943        'args_capi': {isrequired: ',&#varname#_capi'},
944        'keys_capi': {isoptional: ',&#varname#_capi'},
945        'pyobjfrom': {isintent_inout: """\
946    f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);
947    if (f2py_success) {"""},
948        'closepyobjfrom': {isintent_inout: "    } /*if (f2py_success) of #varname# pyobjfrom*/"},
949        'need': {isintent_inout: 'try_pyarr_from_#ctype#'},
950        '_check': l_and(isscalar, l_not(iscomplex), l_not(isstring),
951                        isintent_nothide)
952    }, {
953        'frompyobj': [
954            # hasinitvalue...
955            #   if pyobj is None:
956            #     varname = init
957            #   else
958            #     from_pyobj(varname)
959            #
960            # isoptional and noinitvalue...
961            #   if pyobj is not None:
962            #     from_pyobj(varname)
963            #   else:
964            #     varname is uninitialized
965            #
966            # ...
967            #   from_pyobj(varname)
968            #
969            {hasinitvalue: '    if (#varname#_capi == Py_None) #varname# = #init#; else',
970             '_depend': ''},
971            {l_and(isoptional, l_not(hasinitvalue)): '    if (#varname#_capi != Py_None)',
972             '_depend': ''},
973            {l_not(islogical): '''\
974        f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");
975    if (f2py_success) {'''},
976            {islogical: '''\
977        #varname# = (#ctype#)PyObject_IsTrue(#varname#_capi);
978        f2py_success = 1;
979    if (f2py_success) {'''},
980        ],
981        'cleanupfrompyobj': '    } /*if (f2py_success) of #varname#*/',
982        'need': {l_not(islogical): '#ctype#_from_pyobj'},
983        '_check': l_and(isscalar, l_not(iscomplex), isintent_nothide),
984        '_depend': ''
985    }, {  # Hidden
986        'frompyobj': {hasinitvalue: '    #varname# = #init#;'},
987        'need': typedef_need_dict,
988        '_check': l_and(isscalar, l_not(iscomplex), isintent_hide),
989        '_depend': ''
990    }, {  # Common
991        'frompyobj': {debugcapi: '    fprintf(stderr,"#vardebugshowvalue#\\n",#varname#);'},
992        '_check': l_and(isscalar, l_not(iscomplex)),
993        '_depend': ''
994    },
995    # Complex scalars
996    {  # Common
997        'decl': '    #ctype# #varname#;',
998        'callfortran': {isintent_c: '#varname#,', l_not(isintent_c): '&#varname#,'},
999        'pyobjfrom': {debugcapi: '    fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},
1000        'return': {isintent_out: ',#varname#_capi'},
1001        '_check': iscomplex
1002    }, {  # Not hidden
1003        'decl': '    PyObject *#varname#_capi = Py_None;',
1004        'argformat': {isrequired: 'O'},
1005        'keyformat': {isoptional: 'O'},
1006        'args_capi': {isrequired: ',&#varname#_capi'},
1007        'keys_capi': {isoptional: ',&#varname#_capi'},
1008        'need': {isintent_inout: 'try_pyarr_from_#ctype#'},
1009        'pyobjfrom': {isintent_inout: """\
1010        f2py_success = try_pyarr_from_#ctype#(#varname#_capi,&#varname#);
1011        if (f2py_success) {"""},
1012        'closepyobjfrom': {isintent_inout: "        } /*if (f2py_success) of #varname# pyobjfrom*/"},
1013        '_check': l_and(iscomplex, isintent_nothide)
1014    }, {
1015        'frompyobj': [{hasinitvalue: '    if (#varname#_capi==Py_None) {#varname#.r = #init.r#, #varname#.i = #init.i#;} else'},
1016                      {l_and(isoptional, l_not(hasinitvalue))
1017                             : '    if (#varname#_capi != Py_None)'},
1018                      '        f2py_success = #ctype#_from_pyobj(&#varname#,#varname#_capi,"#pyname#() #nth# (#varname#) can\'t be converted to #ctype#");'
1019                      '\n    if (f2py_success) {'],
1020        'cleanupfrompyobj': '    }  /*if (f2py_success) of #varname# frompyobj*/',
1021        'need': ['#ctype#_from_pyobj'],
1022        '_check': l_and(iscomplex, isintent_nothide),
1023        '_depend': ''
1024    }, {  # Hidden
1025        'decl': {isintent_out: '    PyObject *#varname#_capi = Py_None;'},
1026        '_check': l_and(iscomplex, isintent_hide)
1027    }, {
1028        'frompyobj': {hasinitvalue: '    #varname#.r = #init.r#, #varname#.i = #init.i#;'},
1029        '_check': l_and(iscomplex, isintent_hide),
1030        '_depend': ''
1031    }, {  # Common
1032        'pyobjfrom': {isintent_out: '    #varname#_capi = pyobj_from_#ctype#1(#varname#);'},
1033        'need': ['pyobj_from_#ctype#1'],
1034        '_check': iscomplex
1035    }, {
1036        'frompyobj': {debugcapi: '    fprintf(stderr,"#vardebugshowvalue#\\n",#varname#.r,#varname#.i);'},
1037        '_check': iscomplex,
1038        '_depend': ''
1039    },
1040    # String
1041    {  # Common
1042        'decl': ['    #ctype# #varname# = NULL;',
1043                 '    int slen(#varname#);',
1044                 '    PyObject *#varname#_capi = Py_None;'],
1045        'callfortran': '#varname#,',
1046        'callfortranappend': 'slen(#varname#),',
1047        'pyobjfrom': [
1048            {debugcapi:
1049             '    fprintf(stderr,'
1050             '"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},
1051            # The trailing null value for Fortran is blank.
1052            {l_and(isintent_out, l_not(isintent_c)):
1053             "        STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},
1054        ],
1055        'return': {isintent_out: ',#varname#'},
1056        'need': ['len..',
1057                 {l_and(isintent_out, l_not(isintent_c)): 'STRINGPADN'}],
1058        '_check': isstring
1059    }, {  # Common
1060        'frompyobj': [
1061            """\
1062    slen(#varname#) = #elsize#;
1063    f2py_success = #ctype#_from_pyobj(&#varname#,&slen(#varname#),#init#,"""
1064"""#varname#_capi,\"#ctype#_from_pyobj failed in converting #nth#"""
1065"""`#varname#\' of #pyname# to C #ctype#\");
1066    if (f2py_success) {""",
1067            # The trailing null value for Fortran is blank.
1068            {l_not(isintent_c):
1069             "        STRINGPADN(#varname#, slen(#varname#), '\\0', ' ');"},
1070        ],
1071        'cleanupfrompyobj': """\
1072        STRINGFREE(#varname#);
1073    }  /*if (f2py_success) of #varname#*/""",
1074        'need': ['#ctype#_from_pyobj', 'len..', 'STRINGFREE',
1075                 {l_not(isintent_c): 'STRINGPADN'}],
1076        '_check': isstring,
1077        '_depend': ''
1078    }, {  # Not hidden
1079        'argformat': {isrequired: 'O'},
1080        'keyformat': {isoptional: 'O'},
1081        'args_capi': {isrequired: ',&#varname#_capi'},
1082        'keys_capi': {isoptional: ',&#varname#_capi'},
1083        'pyobjfrom': [
1084            {l_and(isintent_inout, l_not(isintent_c)):
1085             "        STRINGPADN(#varname#, slen(#varname#), ' ', '\\0');"},
1086            {isintent_inout: '''\
1087    f2py_success = try_pyarr_from_#ctype#(#varname#_capi, #varname#,
1088                                          slen(#varname#));
1089    if (f2py_success) {'''}],
1090        'closepyobjfrom': {isintent_inout: '    } /*if (f2py_success) of #varname# pyobjfrom*/'},
1091        'need': {isintent_inout: 'try_pyarr_from_#ctype#',
1092                 l_and(isintent_inout, l_not(isintent_c)): 'STRINGPADN'},
1093        '_check': l_and(isstring, isintent_nothide)
1094    }, {  # Hidden
1095        '_check': l_and(isstring, isintent_hide)
1096    }, {
1097        'frompyobj': {debugcapi: '    fprintf(stderr,"#vardebugshowvalue#\\n",slen(#varname#),#varname#);'},
1098        '_check': isstring,
1099        '_depend': ''
1100    },
1101    # Array
1102    {  # Common
1103        'decl': ['    #ctype# *#varname# = NULL;',
1104                 '    npy_intp #varname#_Dims[#rank#] = {#rank*[-1]#};',
1105                 '    const int #varname#_Rank = #rank#;',
1106                 '    PyArrayObject *capi_#varname#_as_array = NULL;',
1107                 '    int capi_#varname#_intent = 0;',
1108                 {isstringarray: '    int slen(#varname#) = 0;'},
1109                 ],
1110        'callfortran': '#varname#,',
1111        'callfortranappend': {isstringarray: 'slen(#varname#),'},
1112        'return': {isintent_out: ',capi_#varname#_as_array'},
1113        'need': 'len..',
1114        '_check': isarray
1115    }, {  # intent(overwrite) array
1116        'decl': '    int capi_overwrite_#varname# = 1;',
1117        'kwlistxa': '"overwrite_#varname#",',
1118        'xaformat': 'i',
1119        'keys_xa': ',&capi_overwrite_#varname#',
1120        'docsignxa': 'overwrite_#varname#=1,',
1121        'docsignxashort': 'overwrite_#varname#,',
1122        'docstropt': 'overwrite_#varname# : input int, optional\\n    Default: 1',
1123        '_check': l_and(isarray, isintent_overwrite),
1124    }, {
1125        'frompyobj': '    capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',
1126        '_check': l_and(isarray, isintent_overwrite),
1127        '_depend': '',
1128    },
1129    {  # intent(copy) array
1130        'decl': '    int capi_overwrite_#varname# = 0;',
1131        'kwlistxa': '"overwrite_#varname#",',
1132        'xaformat': 'i',
1133        'keys_xa': ',&capi_overwrite_#varname#',
1134        'docsignxa': 'overwrite_#varname#=0,',
1135        'docsignxashort': 'overwrite_#varname#,',
1136        'docstropt': 'overwrite_#varname# : input int, optional\\n    Default: 0',
1137        '_check': l_and(isarray, isintent_copy),
1138    }, {
1139        'frompyobj': '    capi_#varname#_intent |= (capi_overwrite_#varname#?0:F2PY_INTENT_COPY);',
1140        '_check': l_and(isarray, isintent_copy),
1141        '_depend': '',
1142    }, {
1143        'need': [{hasinitvalue: 'forcomb'}, {hasinitvalue: 'CFUNCSMESS'}],
1144        '_check': isarray,
1145        '_depend': ''
1146    }, {  # Not hidden
1147        'decl': '    PyObject *#varname#_capi = Py_None;',
1148        'argformat': {isrequired: 'O'},
1149        'keyformat': {isoptional: 'O'},
1150        'args_capi': {isrequired: ',&#varname#_capi'},
1151        'keys_capi': {isoptional: ',&#varname#_capi'},
1152        '_check': l_and(isarray, isintent_nothide)
1153    }, {
1154        'frompyobj': [
1155            '    #setdims#;',
1156            '    capi_#varname#_intent |= #intent#;',
1157            ('    const char capi_errmess[] = "#modulename#.#pyname#:'
1158             ' failed to create array from the #nth# `#varname#`";'),
1159            {isintent_hide:
1160             '    capi_#varname#_as_array = ndarray_from_pyobj('
1161             '  #atype#,#elsize#,#varname#_Dims,#varname#_Rank,'
1162             '  capi_#varname#_intent,Py_None,capi_errmess);'},
1163            {isintent_nothide:
1164             '    capi_#varname#_as_array = ndarray_from_pyobj('
1165             '  #atype#,#elsize#,#varname#_Dims,#varname#_Rank,'
1166             '  capi_#varname#_intent,#varname#_capi,capi_errmess);'},
1167            """\
1168    if (capi_#varname#_as_array == NULL) {
1169        PyObject* capi_err = PyErr_Occurred();
1170        if (capi_err == NULL) {
1171            capi_err = #modulename#_error;
1172            PyErr_SetString(capi_err, capi_errmess);
1173        }
1174    } else {
1175        #varname# = (#ctype# *)(PyArray_DATA(capi_#varname#_as_array));
1176""",
1177            {isstringarray:
1178             '    slen(#varname#) = f2py_itemsize(#varname#);'},
1179            {hasinitvalue: [
1180                {isintent_nothide:
1181                 '    if (#varname#_capi == Py_None) {'},
1182                {isintent_hide: '    {'},
1183                {iscomplexarray: '        #ctype# capi_c;'},
1184                """\
1185        int *_i,capi_i=0;
1186        CFUNCSMESS(\"#name#: Initializing #varname#=#init#\\n\");
1187        struct ForcombCache cache;
1188        if (initforcomb(&cache, PyArray_DIMS(capi_#varname#_as_array),
1189                        PyArray_NDIM(capi_#varname#_as_array),1)) {
1190            while ((_i = nextforcomb(&cache)))
1191                #varname#[capi_i++] = #init#; /* fortran way */
1192        } else {
1193            PyObject *exc, *val, *tb;
1194            PyErr_Fetch(&exc, &val, &tb);
1195            PyErr_SetString(exc ? exc : #modulename#_error,
1196                \"Initialization of #nth# #varname# failed (initforcomb).\");
1197            npy_PyErr_ChainExceptionsCause(exc, val, tb);
1198            f2py_success = 0;
1199        }
1200    }

Showing the first 1,200 of 1630 lines. Download the file for the rest.

codekingpro/portable-devtools · Team Ai