rules.py 57 KB

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