cfuncs.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  1. """
  2. C declarations, CPP macros, and C functions for f2py2e.
  3. Only required declarations/macros/functions will be used.
  4. Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
  5. Copyright 2011 -- present NumPy Developers.
  6. Permission to use, modify, and distribute this software is given under the
  7. terms of the NumPy License.
  8. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  9. """
  10. import sys
  11. import copy
  12. from . import __version__
  13. f2py_version = __version__.version
  14. def errmess(s: str) -> None:
  15. """
  16. Write an error message to stderr.
  17. This indirection is needed because sys.stderr might not always be available (see #26862).
  18. """
  19. if sys.stderr is not None:
  20. sys.stderr.write(s)
  21. ##################### Definitions ##################
  22. outneeds = {'includes0': [], 'includes': [], 'typedefs': [], 'typedefs_generated': [],
  23. 'userincludes': [],
  24. 'cppmacros': [], 'cfuncs': [], 'callbacks': [], 'f90modhooks': [],
  25. 'commonhooks': []}
  26. needs = {}
  27. includes0 = {'includes0': '/*need_includes0*/'}
  28. includes = {'includes': '/*need_includes*/'}
  29. userincludes = {'userincludes': '/*need_userincludes*/'}
  30. typedefs = {'typedefs': '/*need_typedefs*/'}
  31. typedefs_generated = {'typedefs_generated': '/*need_typedefs_generated*/'}
  32. cppmacros = {'cppmacros': '/*need_cppmacros*/'}
  33. cfuncs = {'cfuncs': '/*need_cfuncs*/'}
  34. callbacks = {'callbacks': '/*need_callbacks*/'}
  35. f90modhooks = {'f90modhooks': '/*need_f90modhooks*/',
  36. 'initf90modhooksstatic': '/*initf90modhooksstatic*/',
  37. 'initf90modhooksdynamic': '/*initf90modhooksdynamic*/',
  38. }
  39. commonhooks = {'commonhooks': '/*need_commonhooks*/',
  40. 'initcommonhooks': '/*need_initcommonhooks*/',
  41. }
  42. ############ Includes ###################
  43. includes0['math.h'] = '#include <math.h>'
  44. includes0['string.h'] = '#include <string.h>'
  45. includes0['setjmp.h'] = '#include <setjmp.h>'
  46. includes['arrayobject.h'] = '''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API
  47. #include "arrayobject.h"'''
  48. includes['npy_math.h'] = '#include "numpy/npy_math.h"'
  49. includes['arrayobject.h'] = '#include "fortranobject.h"'
  50. includes['stdarg.h'] = '#include <stdarg.h>'
  51. ############# Type definitions ###############
  52. typedefs['unsigned_char'] = 'typedef unsigned char unsigned_char;'
  53. typedefs['unsigned_short'] = 'typedef unsigned short unsigned_short;'
  54. typedefs['unsigned_long'] = 'typedef unsigned long unsigned_long;'
  55. typedefs['signed_char'] = 'typedef signed char signed_char;'
  56. typedefs['long_long'] = """
  57. #if defined(NPY_OS_WIN32)
  58. typedef __int64 long_long;
  59. #else
  60. typedef long long long_long;
  61. typedef unsigned long long unsigned_long_long;
  62. #endif
  63. """
  64. typedefs['unsigned_long_long'] = """
  65. #if defined(NPY_OS_WIN32)
  66. typedef __uint64 long_long;
  67. #else
  68. typedef unsigned long long unsigned_long_long;
  69. #endif
  70. """
  71. typedefs['long_double'] = """
  72. #ifndef _LONG_DOUBLE
  73. typedef long double long_double;
  74. #endif
  75. """
  76. typedefs[
  77. 'complex_long_double'] = 'typedef struct {long double r,i;} complex_long_double;'
  78. typedefs['complex_float'] = 'typedef struct {float r,i;} complex_float;'
  79. typedefs['complex_double'] = 'typedef struct {double r,i;} complex_double;'
  80. typedefs['string'] = """typedef char * string;"""
  81. typedefs['character'] = """typedef char character;"""
  82. ############### CPP macros ####################
  83. cppmacros['CFUNCSMESS'] = """
  84. #ifdef DEBUGCFUNCS
  85. #define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess);
  86. #define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\
  87. PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
  88. fprintf(stderr,\"\\n\");
  89. #else
  90. #define CFUNCSMESS(mess)
  91. #define CFUNCSMESSPY(mess,obj)
  92. #endif
  93. """
  94. cppmacros['F_FUNC'] = """
  95. #if defined(PREPEND_FORTRAN)
  96. #if defined(NO_APPEND_FORTRAN)
  97. #if defined(UPPERCASE_FORTRAN)
  98. #define F_FUNC(f,F) _##F
  99. #else
  100. #define F_FUNC(f,F) _##f
  101. #endif
  102. #else
  103. #if defined(UPPERCASE_FORTRAN)
  104. #define F_FUNC(f,F) _##F##_
  105. #else
  106. #define F_FUNC(f,F) _##f##_
  107. #endif
  108. #endif
  109. #else
  110. #if defined(NO_APPEND_FORTRAN)
  111. #if defined(UPPERCASE_FORTRAN)
  112. #define F_FUNC(f,F) F
  113. #else
  114. #define F_FUNC(f,F) f
  115. #endif
  116. #else
  117. #if defined(UPPERCASE_FORTRAN)
  118. #define F_FUNC(f,F) F##_
  119. #else
  120. #define F_FUNC(f,F) f##_
  121. #endif
  122. #endif
  123. #endif
  124. #if defined(UNDERSCORE_G77)
  125. #define F_FUNC_US(f,F) F_FUNC(f##_,F##_)
  126. #else
  127. #define F_FUNC_US(f,F) F_FUNC(f,F)
  128. #endif
  129. """
  130. cppmacros['F_WRAPPEDFUNC'] = """
  131. #if defined(PREPEND_FORTRAN)
  132. #if defined(NO_APPEND_FORTRAN)
  133. #if defined(UPPERCASE_FORTRAN)
  134. #define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F
  135. #else
  136. #define F_WRAPPEDFUNC(f,F) _f2pywrap##f
  137. #endif
  138. #else
  139. #if defined(UPPERCASE_FORTRAN)
  140. #define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_
  141. #else
  142. #define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_
  143. #endif
  144. #endif
  145. #else
  146. #if defined(NO_APPEND_FORTRAN)
  147. #if defined(UPPERCASE_FORTRAN)
  148. #define F_WRAPPEDFUNC(f,F) F2PYWRAP##F
  149. #else
  150. #define F_WRAPPEDFUNC(f,F) f2pywrap##f
  151. #endif
  152. #else
  153. #if defined(UPPERCASE_FORTRAN)
  154. #define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_
  155. #else
  156. #define F_WRAPPEDFUNC(f,F) f2pywrap##f##_
  157. #endif
  158. #endif
  159. #endif
  160. #if defined(UNDERSCORE_G77)
  161. #define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_)
  162. #else
  163. #define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F)
  164. #endif
  165. """
  166. cppmacros['F_MODFUNC'] = """
  167. #if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */
  168. #if defined(NO_APPEND_FORTRAN)
  169. #define F_MODFUNCNAME(m,f) $ ## m ## $ ## f
  170. #else
  171. #define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _
  172. #endif
  173. #endif
  174. #if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */
  175. #if defined(NO_APPEND_FORTRAN)
  176. #define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f
  177. #else
  178. #define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _
  179. #endif
  180. #endif
  181. #if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */
  182. #if defined(NO_APPEND_FORTRAN)
  183. #define F_MODFUNCNAME(m,f) f ## .in. ## m
  184. #else
  185. #define F_MODFUNCNAME(m,f) f ## .in. ## m ## _
  186. #endif
  187. #endif
  188. /*
  189. #if defined(UPPERCASE_FORTRAN)
  190. #define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F)
  191. #else
  192. #define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f)
  193. #endif
  194. */
  195. #define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f))
  196. """
  197. cppmacros['SWAPUNSAFE'] = """
  198. #define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\
  199. (size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\
  200. (size_t)(a) = ((size_t)(a) ^ (size_t)(b))
  201. """
  202. cppmacros['SWAP'] = """
  203. #define SWAP(a,b,t) {\\
  204. t *c;\\
  205. c = a;\\
  206. a = b;\\
  207. b = c;}
  208. """
  209. # cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) &
  210. # NPY_ARRAY_C_CONTIGUOUS)'
  211. cppmacros['PRINTPYOBJERR'] = """
  212. #define PRINTPYOBJERR(obj)\\
  213. fprintf(stderr,\"#modulename#.error is related to \");\\
  214. PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
  215. fprintf(stderr,\"\\n\");
  216. """
  217. cppmacros['MINMAX'] = """
  218. #ifndef max
  219. #define max(a,b) ((a > b) ? (a) : (b))
  220. #endif
  221. #ifndef min
  222. #define min(a,b) ((a < b) ? (a) : (b))
  223. #endif
  224. #ifndef MAX
  225. #define MAX(a,b) ((a > b) ? (a) : (b))
  226. #endif
  227. #ifndef MIN
  228. #define MIN(a,b) ((a < b) ? (a) : (b))
  229. #endif
  230. """
  231. cppmacros['len..'] = """
  232. /* See fortranobject.h for definitions. The macros here are provided for BC. */
  233. #define rank f2py_rank
  234. #define shape f2py_shape
  235. #define fshape f2py_shape
  236. #define len f2py_len
  237. #define flen f2py_flen
  238. #define slen f2py_slen
  239. #define size f2py_size
  240. """
  241. cppmacros['pyobj_from_char1'] = r"""
  242. #define pyobj_from_char1(v) (PyLong_FromLong(v))
  243. """
  244. cppmacros['pyobj_from_short1'] = r"""
  245. #define pyobj_from_short1(v) (PyLong_FromLong(v))
  246. """
  247. needs['pyobj_from_int1'] = ['signed_char']
  248. cppmacros['pyobj_from_int1'] = r"""
  249. #define pyobj_from_int1(v) (PyLong_FromLong(v))
  250. """
  251. cppmacros['pyobj_from_long1'] = r"""
  252. #define pyobj_from_long1(v) (PyLong_FromLong(v))
  253. """
  254. needs['pyobj_from_long_long1'] = ['long_long']
  255. cppmacros['pyobj_from_long_long1'] = """
  256. #ifdef HAVE_LONG_LONG
  257. #define pyobj_from_long_long1(v) (PyLong_FromLongLong(v))
  258. #else
  259. #warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long.
  260. #define pyobj_from_long_long1(v) (PyLong_FromLong(v))
  261. #endif
  262. """
  263. needs['pyobj_from_long_double1'] = ['long_double']
  264. cppmacros['pyobj_from_long_double1'] = """
  265. #define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))"""
  266. cppmacros['pyobj_from_double1'] = """
  267. #define pyobj_from_double1(v) (PyFloat_FromDouble(v))"""
  268. cppmacros['pyobj_from_float1'] = """
  269. #define pyobj_from_float1(v) (PyFloat_FromDouble(v))"""
  270. needs['pyobj_from_complex_long_double1'] = ['complex_long_double']
  271. cppmacros['pyobj_from_complex_long_double1'] = """
  272. #define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))"""
  273. needs['pyobj_from_complex_double1'] = ['complex_double']
  274. cppmacros['pyobj_from_complex_double1'] = """
  275. #define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))"""
  276. needs['pyobj_from_complex_float1'] = ['complex_float']
  277. cppmacros['pyobj_from_complex_float1'] = """
  278. #define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))"""
  279. needs['pyobj_from_string1'] = ['string']
  280. cppmacros['pyobj_from_string1'] = """
  281. #define pyobj_from_string1(v) (PyUnicode_FromString((char *)v))"""
  282. needs['pyobj_from_string1size'] = ['string']
  283. cppmacros['pyobj_from_string1size'] = """
  284. #define pyobj_from_string1size(v,len) (PyUnicode_FromStringAndSize((char *)v, len))"""
  285. needs['TRYPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
  286. cppmacros['TRYPYARRAYTEMPLATE'] = """
  287. /* New SciPy */
  288. #define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(PyArray_DATA(arr))=*v; break;
  289. #define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break;
  290. #define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr,PyArray_DATA(arr),pyobj_from_ ## ctype ## 1(*v)); break;
  291. #define TRYPYARRAYTEMPLATE(ctype,typecode) \\
  292. PyArrayObject *arr = NULL;\\
  293. if (!obj) return -2;\\
  294. if (!PyArray_Check(obj)) return -1;\\
  295. if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
  296. if (PyArray_DESCR(arr)->type==typecode) {*(ctype *)(PyArray_DATA(arr))=*v; return 1;}\\
  297. switch (PyArray_TYPE(arr)) {\\
  298. case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\
  299. case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=*v; break;\\
  300. case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=*v; break;\\
  301. case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\
  302. case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\
  303. case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\
  304. case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=(*v!=0); break;\\
  305. case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=*v; break;\\
  306. case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=*v; break;\\
  307. case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=*v; break;\\
  308. case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=*v; break;\\
  309. case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=*v; break;\\
  310. case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=*v; break;\\
  311. case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=*v; break;\\
  312. case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=*v; break;\\
  313. case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
  314. case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
  315. case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_ ## ctype ## 1(*v)); break;\\
  316. default: return -2;\\
  317. };\\
  318. return 1
  319. """
  320. needs['TRYCOMPLEXPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
  321. cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = """
  322. #define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;
  323. #define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\
  324. PyArrayObject *arr = NULL;\\
  325. if (!obj) return -2;\\
  326. if (!PyArray_Check(obj)) return -1;\\
  327. if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYCOMPLEXPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
  328. if (PyArray_DESCR(arr)->type==typecode) {\\
  329. *(ctype *)(PyArray_DATA(arr))=(*v).r;\\
  330. *(ctype *)(PyArray_DATA(arr)+sizeof(ctype))=(*v).i;\\
  331. return 1;\\
  332. }\\
  333. switch (PyArray_TYPE(arr)) {\\
  334. case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r;\\
  335. *(npy_double *)(PyArray_DATA(arr)+sizeof(npy_double))=(*v).i;\\
  336. break;\\
  337. case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r;\\
  338. *(npy_float *)(PyArray_DATA(arr)+sizeof(npy_float))=(*v).i;\\
  339. break;\\
  340. case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r; break;\\
  341. case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=(*v).r; break;\\
  342. case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r; break;\\
  343. case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=(*v).r; break;\\
  344. case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=(*v).r; break;\\
  345. case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=(*v).r; break;\\
  346. case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=(*v).r; break;\\
  347. case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=((*v).r!=0 && (*v).i!=0); break;\\
  348. case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=(*v).r; break;\\
  349. case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=(*v).r; break;\\
  350. case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=(*v).r; break;\\
  351. case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=(*v).r; break;\\
  352. case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=(*v).r; break;\\
  353. case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r; break;\\
  354. case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r;\\
  355. *(npy_longdouble *)(PyArray_DATA(arr)+sizeof(npy_longdouble))=(*v).i;\\
  356. break;\\
  357. case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\\
  358. default: return -2;\\
  359. };\\
  360. return -1;
  361. """
  362. # cppmacros['NUMFROMARROBJ']="""
  363. # define NUMFROMARROBJ(typenum,ctype) \\
  364. # if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
  365. # else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
  366. # if (arr) {\\
  367. # if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
  368. # if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
  369. # goto capi_fail;\\
  370. # } else {\\
  371. # (PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\
  372. # }\\
  373. # if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
  374. # return 1;\\
  375. # }
  376. # """
  377. # XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ
  378. # cppmacros['CNUMFROMARROBJ']="""
  379. # define CNUMFROMARROBJ(typenum,ctype) \\
  380. # if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
  381. # else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
  382. # if (arr) {\\
  383. # if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
  384. # if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
  385. # goto capi_fail;\\
  386. # } else {\\
  387. # (PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\
  388. # }\\
  389. # if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
  390. # return 1;\\
  391. # }
  392. # """
  393. needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR']
  394. cppmacros['GETSTRFROMPYTUPLE'] = """
  395. #define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\
  396. PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\
  397. if (rv_cb_str == NULL)\\
  398. goto capi_fail;\\
  399. if (PyBytes_Check(rv_cb_str)) {\\
  400. str[len-1]='\\0';\\
  401. STRINGCOPYN((str),PyBytes_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\
  402. } else {\\
  403. PRINTPYOBJERR(rv_cb_str);\\
  404. PyErr_SetString(#modulename#_error,\"string object expected\");\\
  405. goto capi_fail;\\
  406. }\\
  407. }
  408. """
  409. cppmacros['GETSCALARFROMPYTUPLE'] = """
  410. #define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\
  411. if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\
  412. if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\
  413. goto capi_fail;\\
  414. }
  415. """
  416. cppmacros['FAILNULL'] = """\
  417. #define FAILNULL(p) do { \\
  418. if ((p) == NULL) { \\
  419. PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\
  420. goto capi_fail; \\
  421. } \\
  422. } while (0)
  423. """
  424. needs['MEMCOPY'] = ['string.h', 'FAILNULL']
  425. cppmacros['MEMCOPY'] = """
  426. #define MEMCOPY(to,from,n)\\
  427. do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0)
  428. """
  429. cppmacros['STRINGMALLOC'] = """
  430. #define STRINGMALLOC(str,len)\\
  431. if ((str = (string)malloc(len+1)) == NULL) {\\
  432. PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\
  433. goto capi_fail;\\
  434. } else {\\
  435. (str)[len] = '\\0';\\
  436. }
  437. """
  438. cppmacros['STRINGFREE'] = """
  439. #define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0)
  440. """
  441. needs['STRINGPADN'] = ['string.h']
  442. cppmacros['STRINGPADN'] = """
  443. /*
  444. STRINGPADN replaces null values with padding values from the right.
  445. `to` must have size of at least N bytes.
  446. If the `to[N-1]` has null value, then replace it and all the
  447. preceding, nulls with the given padding.
  448. STRINGPADN(to, N, PADDING, NULLVALUE) is an inverse operation.
  449. */
  450. #define STRINGPADN(to, N, NULLVALUE, PADDING) \\
  451. do { \\
  452. int _m = (N); \\
  453. char *_to = (to); \\
  454. for (_m -= 1; _m >= 0 && _to[_m] == NULLVALUE; _m--) { \\
  455. _to[_m] = PADDING; \\
  456. } \\
  457. } while (0)
  458. """
  459. needs['STRINGCOPYN'] = ['string.h', 'FAILNULL']
  460. cppmacros['STRINGCOPYN'] = """
  461. /*
  462. STRINGCOPYN copies N bytes.
  463. `to` and `from` buffers must have sizes of at least N bytes.
  464. */
  465. #define STRINGCOPYN(to,from,N) \\
  466. do { \\
  467. int _m = (N); \\
  468. char *_to = (to); \\
  469. char *_from = (from); \\
  470. FAILNULL(_to); FAILNULL(_from); \\
  471. (void)strncpy(_to, _from, _m); \\
  472. } while (0)
  473. """
  474. needs['STRINGCOPY'] = ['string.h', 'FAILNULL']
  475. cppmacros['STRINGCOPY'] = """
  476. #define STRINGCOPY(to,from)\\
  477. do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0)
  478. """
  479. cppmacros['CHECKGENERIC'] = """
  480. #define CHECKGENERIC(check,tcheck,name) \\
  481. if (!(check)) {\\
  482. PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
  483. /*goto capi_fail;*/\\
  484. } else """
  485. cppmacros['CHECKARRAY'] = """
  486. #define CHECKARRAY(check,tcheck,name) \\
  487. if (!(check)) {\\
  488. PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
  489. /*goto capi_fail;*/\\
  490. } else """
  491. cppmacros['CHECKSTRING'] = """
  492. #define CHECKSTRING(check,tcheck,name,show,var)\\
  493. if (!(check)) {\\
  494. char errstring[256];\\
  495. sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\
  496. PyErr_SetString(#modulename#_error, errstring);\\
  497. /*goto capi_fail;*/\\
  498. } else """
  499. cppmacros['CHECKSCALAR'] = """
  500. #define CHECKSCALAR(check,tcheck,name,show,var)\\
  501. if (!(check)) {\\
  502. char errstring[256];\\
  503. sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\
  504. PyErr_SetString(#modulename#_error,errstring);\\
  505. /*goto capi_fail;*/\\
  506. } else """
  507. # cppmacros['CHECKDIMS']="""
  508. # define CHECKDIMS(dims,rank) \\
  509. # for (int i=0;i<(rank);i++)\\
  510. # if (dims[i]<0) {\\
  511. # fprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\
  512. # goto capi_fail;\\
  513. # }
  514. # """
  515. cppmacros[
  516. 'ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))'
  517. cppmacros['OLDPYNUM'] = """
  518. #ifdef OLDPYNUM
  519. #error You need to install NumPy version 0.13 or higher. See https://scipy.org/install.html
  520. #endif
  521. """
  522. # Defining the correct value to indicate thread-local storage in C without
  523. # running a compile-time check (which we have no control over in generated
  524. # code used outside of NumPy) is hard. Therefore we support overriding this
  525. # via an external define - the f2py-using package can then use the same
  526. # compile-time checks as we use for `NPY_TLS` when building NumPy (see
  527. # scipy#21860 for an example of that).
  528. #
  529. # __STDC_NO_THREADS__ should not be coupled to the availability of _Thread_local.
  530. # In case we get a bug report, guard it with __STDC_NO_THREADS__ after all.
  531. #
  532. # `thread_local` has become a keyword in C23, but don't try to use that yet
  533. # (too new, doing so while C23 support is preliminary will likely cause more
  534. # problems than it solves).
  535. #
  536. # Note: do not try to use `threads.h`, its availability is very low
  537. # *and* threads.h isn't actually used where `F2PY_THREAD_LOCAL_DECL` is
  538. # in the generated code. See gh-27718 for more details.
  539. cppmacros["F2PY_THREAD_LOCAL_DECL"] = """
  540. #ifndef F2PY_THREAD_LOCAL_DECL
  541. #if defined(_MSC_VER)
  542. #define F2PY_THREAD_LOCAL_DECL __declspec(thread)
  543. #elif defined(NPY_OS_MINGW)
  544. #define F2PY_THREAD_LOCAL_DECL __thread
  545. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  546. #define F2PY_THREAD_LOCAL_DECL _Thread_local
  547. #elif defined(__GNUC__) \\
  548. && (__GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 4)))
  549. #define F2PY_THREAD_LOCAL_DECL __thread
  550. #endif
  551. #endif
  552. """
  553. ################# C functions ###############
  554. cfuncs['calcarrindex'] = """
  555. static int calcarrindex(int *i,PyArrayObject *arr) {
  556. int k,ii = i[0];
  557. for (k=1; k < PyArray_NDIM(arr); k++)
  558. ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */
  559. return ii;
  560. }"""
  561. cfuncs['calcarrindextr'] = """
  562. static int calcarrindextr(int *i,PyArrayObject *arr) {
  563. int k,ii = i[PyArray_NDIM(arr)-1];
  564. for (k=1; k < PyArray_NDIM(arr); k++)
  565. ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */
  566. return ii;
  567. }"""
  568. cfuncs['forcomb'] = """
  569. static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache;
  570. static int initforcomb(npy_intp *dims,int nd,int tr) {
  571. int k;
  572. if (dims==NULL) return 0;
  573. if (nd<0) return 0;
  574. forcombcache.nd = nd;
  575. forcombcache.d = dims;
  576. forcombcache.tr = tr;
  577. if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
  578. if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
  579. for (k=1;k<nd;k++) {
  580. forcombcache.i[k] = forcombcache.i_tr[nd-k-1] = 0;
  581. }
  582. forcombcache.i[0] = forcombcache.i_tr[nd-1] = -1;
  583. return 1;
  584. }
  585. static int *nextforcomb(void) {
  586. int j,*i,*i_tr,k;
  587. int nd=forcombcache.nd;
  588. if ((i=forcombcache.i) == NULL) return NULL;
  589. if ((i_tr=forcombcache.i_tr) == NULL) return NULL;
  590. if (forcombcache.d == NULL) return NULL;
  591. i[0]++;
  592. if (i[0]==forcombcache.d[0]) {
  593. j=1;
  594. while ((j<nd) && (i[j]==forcombcache.d[j]-1)) j++;
  595. if (j==nd) {
  596. free(i);
  597. free(i_tr);
  598. return NULL;
  599. }
  600. for (k=0;k<j;k++) i[k] = i_tr[nd-k-1] = 0;
  601. i[j]++;
  602. i_tr[nd-j-1]++;
  603. } else
  604. i_tr[nd-1]++;
  605. if (forcombcache.tr) return i_tr;
  606. return i;
  607. }"""
  608. needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string']
  609. cfuncs['try_pyarr_from_string'] = """
  610. /*
  611. try_pyarr_from_string copies str[:len(obj)] to the data of an `ndarray`.
  612. If obj is an `ndarray`, it is assumed to be contiguous.
  613. If the specified len==-1, str must be null-terminated.
  614. */
  615. static int try_pyarr_from_string(PyObject *obj,
  616. const string str, const int len) {
  617. #ifdef DEBUGCFUNCS
  618. fprintf(stderr, "try_pyarr_from_string(str='%s', len=%d, obj=%p)\\n",
  619. (char*)str,len, obj);
  620. #endif
  621. if (!obj) return -2; /* Object missing */
  622. if (obj == Py_None) return -1; /* None */
  623. if (!PyArray_Check(obj)) goto capi_fail; /* not an ndarray */
  624. if (PyArray_Check(obj)) {
  625. PyArrayObject *arr = (PyArrayObject *)obj;
  626. assert(ISCONTIGUOUS(arr));
  627. string buf = PyArray_DATA(arr);
  628. npy_intp n = len;
  629. if (n == -1) {
  630. /* Assuming null-terminated str. */
  631. n = strlen(str);
  632. }
  633. if (n > PyArray_NBYTES(arr)) {
  634. n = PyArray_NBYTES(arr);
  635. }
  636. STRINGCOPYN(buf, str, n);
  637. return 1;
  638. }
  639. capi_fail:
  640. PRINTPYOBJERR(obj);
  641. PyErr_SetString(#modulename#_error, \"try_pyarr_from_string failed\");
  642. return 0;
  643. }
  644. """
  645. needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN']
  646. cfuncs['string_from_pyobj'] = """
  647. /*
  648. Create a new string buffer `str` of at most length `len` from a
  649. Python string-like object `obj`.
  650. The string buffer has given size (len) or the size of inistr when len==-1.
  651. The string buffer is padded with blanks: in Fortran, trailing blanks
  652. are insignificant contrary to C nulls.
  653. */
  654. static int
  655. string_from_pyobj(string *str, int *len, const string inistr, PyObject *obj,
  656. const char *errmess)
  657. {
  658. PyObject *tmp = NULL;
  659. string buf = NULL;
  660. npy_intp n = -1;
  661. #ifdef DEBUGCFUNCS
  662. fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",
  663. (char*)str, *len, (char *)inistr, obj);
  664. #endif
  665. if (obj == Py_None) {
  666. n = strlen(inistr);
  667. buf = inistr;
  668. }
  669. else if (PyArray_Check(obj)) {
  670. PyArrayObject *arr = (PyArrayObject *)obj;
  671. if (!ISCONTIGUOUS(arr)) {
  672. PyErr_SetString(PyExc_ValueError,
  673. \"array object is non-contiguous.\");
  674. goto capi_fail;
  675. }
  676. n = PyArray_NBYTES(arr);
  677. buf = PyArray_DATA(arr);
  678. n = strnlen(buf, n);
  679. }
  680. else {
  681. if (PyBytes_Check(obj)) {
  682. tmp = obj;
  683. Py_INCREF(tmp);
  684. }
  685. else if (PyUnicode_Check(obj)) {
  686. tmp = PyUnicode_AsASCIIString(obj);
  687. }
  688. else {
  689. PyObject *tmp2;
  690. tmp2 = PyObject_Str(obj);
  691. if (tmp2) {
  692. tmp = PyUnicode_AsASCIIString(tmp2);
  693. Py_DECREF(tmp2);
  694. }
  695. else {
  696. tmp = NULL;
  697. }
  698. }
  699. if (tmp == NULL) goto capi_fail;
  700. n = PyBytes_GET_SIZE(tmp);
  701. buf = PyBytes_AS_STRING(tmp);
  702. }
  703. if (*len == -1) {
  704. /* TODO: change the type of `len` so that we can remove this */
  705. if (n > NPY_MAX_INT) {
  706. PyErr_SetString(PyExc_OverflowError,
  707. "object too large for a 32-bit int");
  708. goto capi_fail;
  709. }
  710. *len = n;
  711. }
  712. else if (*len < n) {
  713. /* discard the last (len-n) bytes of input buf */
  714. n = *len;
  715. }
  716. if (n < 0 || *len < 0 || buf == NULL) {
  717. goto capi_fail;
  718. }
  719. STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1)
  720. if (n < *len) {
  721. /*
  722. Pad fixed-width string with nulls. The caller will replace
  723. nulls with blanks when the corresponding argument is not
  724. intent(c).
  725. */
  726. memset(*str + n, '\\0', *len - n);
  727. }
  728. STRINGCOPYN(*str, buf, n);
  729. Py_XDECREF(tmp);
  730. return 1;
  731. capi_fail:
  732. Py_XDECREF(tmp);
  733. {
  734. PyObject* err = PyErr_Occurred();
  735. if (err == NULL) {
  736. err = #modulename#_error;
  737. }
  738. PyErr_SetString(err, errmess);
  739. }
  740. return 0;
  741. }
  742. """
  743. cfuncs['character_from_pyobj'] = """
  744. static int
  745. character_from_pyobj(character* v, PyObject *obj, const char *errmess) {
  746. if (PyBytes_Check(obj)) {
  747. /* empty bytes has trailing null, so dereferencing is always safe */
  748. *v = PyBytes_AS_STRING(obj)[0];
  749. return 1;
  750. } else if (PyUnicode_Check(obj)) {
  751. PyObject* tmp = PyUnicode_AsASCIIString(obj);
  752. if (tmp != NULL) {
  753. *v = PyBytes_AS_STRING(tmp)[0];
  754. Py_DECREF(tmp);
  755. return 1;
  756. }
  757. } else if (PyArray_Check(obj)) {
  758. PyArrayObject* arr = (PyArrayObject*)obj;
  759. if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) {
  760. *v = PyArray_BYTES(arr)[0];
  761. return 1;
  762. } else if (F2PY_IS_UNICODE_ARRAY(arr)) {
  763. // TODO: update when numpy will support 1-byte and
  764. // 2-byte unicode dtypes
  765. PyObject* tmp = PyUnicode_FromKindAndData(
  766. PyUnicode_4BYTE_KIND,
  767. PyArray_BYTES(arr),
  768. (PyArray_NBYTES(arr)>0?1:0));
  769. if (tmp != NULL) {
  770. if (character_from_pyobj(v, tmp, errmess)) {
  771. Py_DECREF(tmp);
  772. return 1;
  773. }
  774. Py_DECREF(tmp);
  775. }
  776. }
  777. } else if (PySequence_Check(obj)) {
  778. PyObject* tmp = PySequence_GetItem(obj,0);
  779. if (tmp != NULL) {
  780. if (character_from_pyobj(v, tmp, errmess)) {
  781. Py_DECREF(tmp);
  782. return 1;
  783. }
  784. Py_DECREF(tmp);
  785. }
  786. }
  787. {
  788. /* TODO: This error (and most other) error handling needs cleaning. */
  789. char mess[F2PY_MESSAGE_BUFFER_SIZE];
  790. strcpy(mess, errmess);
  791. PyObject* err = PyErr_Occurred();
  792. if (err == NULL) {
  793. err = PyExc_TypeError;
  794. Py_INCREF(err);
  795. }
  796. else {
  797. Py_INCREF(err);
  798. PyErr_Clear();
  799. }
  800. sprintf(mess + strlen(mess),
  801. " -- expected str|bytes|sequence-of-str-or-bytes, got ");
  802. f2py_describe(obj, mess + strlen(mess));
  803. PyErr_SetString(err, mess);
  804. Py_DECREF(err);
  805. }
  806. return 0;
  807. }
  808. """
  809. # TODO: These should be dynamically generated, too many mapped to int things,
  810. # see note in _isocbind.py
  811. needs['char_from_pyobj'] = ['int_from_pyobj']
  812. cfuncs['char_from_pyobj'] = """
  813. static int
  814. char_from_pyobj(char* v, PyObject *obj, const char *errmess) {
  815. int i = 0;
  816. if (int_from_pyobj(&i, obj, errmess)) {
  817. *v = (char)i;
  818. return 1;
  819. }
  820. return 0;
  821. }
  822. """
  823. needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char']
  824. cfuncs['signed_char_from_pyobj'] = """
  825. static int
  826. signed_char_from_pyobj(signed_char* v, PyObject *obj, const char *errmess) {
  827. int i = 0;
  828. if (int_from_pyobj(&i, obj, errmess)) {
  829. *v = (signed_char)i;
  830. return 1;
  831. }
  832. return 0;
  833. }
  834. """
  835. needs['short_from_pyobj'] = ['int_from_pyobj']
  836. cfuncs['short_from_pyobj'] = """
  837. static int
  838. short_from_pyobj(short* v, PyObject *obj, const char *errmess) {
  839. int i = 0;
  840. if (int_from_pyobj(&i, obj, errmess)) {
  841. *v = (short)i;
  842. return 1;
  843. }
  844. return 0;
  845. }
  846. """
  847. cfuncs['int_from_pyobj'] = """
  848. static int
  849. int_from_pyobj(int* v, PyObject *obj, const char *errmess)
  850. {
  851. PyObject* tmp = NULL;
  852. if (PyLong_Check(obj)) {
  853. *v = Npy__PyLong_AsInt(obj);
  854. return !(*v == -1 && PyErr_Occurred());
  855. }
  856. tmp = PyNumber_Long(obj);
  857. if (tmp) {
  858. *v = Npy__PyLong_AsInt(tmp);
  859. Py_DECREF(tmp);
  860. return !(*v == -1 && PyErr_Occurred());
  861. }
  862. if (PyComplex_Check(obj)) {
  863. PyErr_Clear();
  864. tmp = PyObject_GetAttrString(obj,\"real\");
  865. }
  866. else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
  867. /*pass*/;
  868. }
  869. else if (PySequence_Check(obj)) {
  870. PyErr_Clear();
  871. tmp = PySequence_GetItem(obj, 0);
  872. }
  873. if (tmp) {
  874. if (int_from_pyobj(v, tmp, errmess)) {
  875. Py_DECREF(tmp);
  876. return 1;
  877. }
  878. Py_DECREF(tmp);
  879. }
  880. {
  881. PyObject* err = PyErr_Occurred();
  882. if (err == NULL) {
  883. err = #modulename#_error;
  884. }
  885. PyErr_SetString(err, errmess);
  886. }
  887. return 0;
  888. }
  889. """
  890. cfuncs['long_from_pyobj'] = """
  891. static int
  892. long_from_pyobj(long* v, PyObject *obj, const char *errmess) {
  893. PyObject* tmp = NULL;
  894. if (PyLong_Check(obj)) {
  895. *v = PyLong_AsLong(obj);
  896. return !(*v == -1 && PyErr_Occurred());
  897. }
  898. tmp = PyNumber_Long(obj);
  899. if (tmp) {
  900. *v = PyLong_AsLong(tmp);
  901. Py_DECREF(tmp);
  902. return !(*v == -1 && PyErr_Occurred());
  903. }
  904. if (PyComplex_Check(obj)) {
  905. PyErr_Clear();
  906. tmp = PyObject_GetAttrString(obj,\"real\");
  907. }
  908. else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
  909. /*pass*/;
  910. }
  911. else if (PySequence_Check(obj)) {
  912. PyErr_Clear();
  913. tmp = PySequence_GetItem(obj, 0);
  914. }
  915. if (tmp) {
  916. if (long_from_pyobj(v, tmp, errmess)) {
  917. Py_DECREF(tmp);
  918. return 1;
  919. }
  920. Py_DECREF(tmp);
  921. }
  922. {
  923. PyObject* err = PyErr_Occurred();
  924. if (err == NULL) {
  925. err = #modulename#_error;
  926. }
  927. PyErr_SetString(err, errmess);
  928. }
  929. return 0;
  930. }
  931. """
  932. needs['long_long_from_pyobj'] = ['long_long']
  933. cfuncs['long_long_from_pyobj'] = """
  934. static int
  935. long_long_from_pyobj(long_long* v, PyObject *obj, const char *errmess)
  936. {
  937. PyObject* tmp = NULL;
  938. if (PyLong_Check(obj)) {
  939. *v = PyLong_AsLongLong(obj);
  940. return !(*v == -1 && PyErr_Occurred());
  941. }
  942. tmp = PyNumber_Long(obj);
  943. if (tmp) {
  944. *v = PyLong_AsLongLong(tmp);
  945. Py_DECREF(tmp);
  946. return !(*v == -1 && PyErr_Occurred());
  947. }
  948. if (PyComplex_Check(obj)) {
  949. PyErr_Clear();
  950. tmp = PyObject_GetAttrString(obj,\"real\");
  951. }
  952. else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
  953. /*pass*/;
  954. }
  955. else if (PySequence_Check(obj)) {
  956. PyErr_Clear();
  957. tmp = PySequence_GetItem(obj, 0);
  958. }
  959. if (tmp) {
  960. if (long_long_from_pyobj(v, tmp, errmess)) {
  961. Py_DECREF(tmp);
  962. return 1;
  963. }
  964. Py_DECREF(tmp);
  965. }
  966. {
  967. PyObject* err = PyErr_Occurred();
  968. if (err == NULL) {
  969. err = #modulename#_error;
  970. }
  971. PyErr_SetString(err,errmess);
  972. }
  973. return 0;
  974. }
  975. """
  976. needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double']
  977. cfuncs['long_double_from_pyobj'] = """
  978. static int
  979. long_double_from_pyobj(long_double* v, PyObject *obj, const char *errmess)
  980. {
  981. double d=0;
  982. if (PyArray_CheckScalar(obj)){
  983. if PyArray_IsScalar(obj, LongDouble) {
  984. PyArray_ScalarAsCtype(obj, v);
  985. return 1;
  986. }
  987. else if (PyArray_Check(obj) && PyArray_TYPE(obj) == NPY_LONGDOUBLE) {
  988. (*v) = *((npy_longdouble *)PyArray_DATA(obj));
  989. return 1;
  990. }
  991. }
  992. if (double_from_pyobj(&d, obj, errmess)) {
  993. *v = (long_double)d;
  994. return 1;
  995. }
  996. return 0;
  997. }
  998. """
  999. cfuncs['double_from_pyobj'] = """
  1000. static int
  1001. double_from_pyobj(double* v, PyObject *obj, const char *errmess)
  1002. {
  1003. PyObject* tmp = NULL;
  1004. if (PyFloat_Check(obj)) {
  1005. *v = PyFloat_AsDouble(obj);
  1006. return !(*v == -1.0 && PyErr_Occurred());
  1007. }
  1008. tmp = PyNumber_Float(obj);
  1009. if (tmp) {
  1010. *v = PyFloat_AsDouble(tmp);
  1011. Py_DECREF(tmp);
  1012. return !(*v == -1.0 && PyErr_Occurred());
  1013. }
  1014. if (PyComplex_Check(obj)) {
  1015. PyErr_Clear();
  1016. tmp = PyObject_GetAttrString(obj,\"real\");
  1017. }
  1018. else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
  1019. /*pass*/;
  1020. }
  1021. else if (PySequence_Check(obj)) {
  1022. PyErr_Clear();
  1023. tmp = PySequence_GetItem(obj, 0);
  1024. }
  1025. if (tmp) {
  1026. if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}
  1027. Py_DECREF(tmp);
  1028. }
  1029. {
  1030. PyObject* err = PyErr_Occurred();
  1031. if (err==NULL) err = #modulename#_error;
  1032. PyErr_SetString(err,errmess);
  1033. }
  1034. return 0;
  1035. }
  1036. """
  1037. needs['float_from_pyobj'] = ['double_from_pyobj']
  1038. cfuncs['float_from_pyobj'] = """
  1039. static int
  1040. float_from_pyobj(float* v, PyObject *obj, const char *errmess)
  1041. {
  1042. double d=0.0;
  1043. if (double_from_pyobj(&d,obj,errmess)) {
  1044. *v = (float)d;
  1045. return 1;
  1046. }
  1047. return 0;
  1048. }
  1049. """
  1050. needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double',
  1051. 'complex_double_from_pyobj', 'npy_math.h']
  1052. cfuncs['complex_long_double_from_pyobj'] = """
  1053. static int
  1054. complex_long_double_from_pyobj(complex_long_double* v, PyObject *obj, const char *errmess)
  1055. {
  1056. complex_double cd = {0.0,0.0};
  1057. if (PyArray_CheckScalar(obj)){
  1058. if PyArray_IsScalar(obj, CLongDouble) {
  1059. PyArray_ScalarAsCtype(obj, v);
  1060. return 1;
  1061. }
  1062. else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) {
  1063. (*v).r = npy_creall(*(((npy_clongdouble *)PyArray_DATA(obj))));
  1064. (*v).i = npy_cimagl(*(((npy_clongdouble *)PyArray_DATA(obj))));
  1065. return 1;
  1066. }
  1067. }
  1068. if (complex_double_from_pyobj(&cd,obj,errmess)) {
  1069. (*v).r = (long_double)cd.r;
  1070. (*v).i = (long_double)cd.i;
  1071. return 1;
  1072. }
  1073. return 0;
  1074. }
  1075. """
  1076. needs['complex_double_from_pyobj'] = ['complex_double', 'npy_math.h']
  1077. cfuncs['complex_double_from_pyobj'] = """
  1078. static int
  1079. complex_double_from_pyobj(complex_double* v, PyObject *obj, const char *errmess) {
  1080. Py_complex c;
  1081. if (PyComplex_Check(obj)) {
  1082. c = PyComplex_AsCComplex(obj);
  1083. (*v).r = c.real;
  1084. (*v).i = c.imag;
  1085. return 1;
  1086. }
  1087. if (PyArray_IsScalar(obj, ComplexFloating)) {
  1088. if (PyArray_IsScalar(obj, CFloat)) {
  1089. npy_cfloat new;
  1090. PyArray_ScalarAsCtype(obj, &new);
  1091. (*v).r = (double)npy_crealf(new);
  1092. (*v).i = (double)npy_cimagf(new);
  1093. }
  1094. else if (PyArray_IsScalar(obj, CLongDouble)) {
  1095. npy_clongdouble new;
  1096. PyArray_ScalarAsCtype(obj, &new);
  1097. (*v).r = (double)npy_creall(new);
  1098. (*v).i = (double)npy_cimagl(new);
  1099. }
  1100. else { /* if (PyArray_IsScalar(obj, CDouble)) */
  1101. PyArray_ScalarAsCtype(obj, v);
  1102. }
  1103. return 1;
  1104. }
  1105. if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */
  1106. PyArrayObject *arr;
  1107. if (PyArray_Check(obj)) {
  1108. arr = (PyArrayObject *)PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE);
  1109. }
  1110. else {
  1111. arr = (PyArrayObject *)PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE));
  1112. }
  1113. if (arr == NULL) {
  1114. return 0;
  1115. }
  1116. (*v).r = npy_creal(*(((npy_cdouble *)PyArray_DATA(arr))));
  1117. (*v).i = npy_cimag(*(((npy_cdouble *)PyArray_DATA(arr))));
  1118. Py_DECREF(arr);
  1119. return 1;
  1120. }
  1121. /* Python does not provide PyNumber_Complex function :-( */
  1122. (*v).i = 0.0;
  1123. if (PyFloat_Check(obj)) {
  1124. (*v).r = PyFloat_AsDouble(obj);
  1125. return !((*v).r == -1.0 && PyErr_Occurred());
  1126. }
  1127. if (PyLong_Check(obj)) {
  1128. (*v).r = PyLong_AsDouble(obj);
  1129. return !((*v).r == -1.0 && PyErr_Occurred());
  1130. }
  1131. if (PySequence_Check(obj) && !(PyBytes_Check(obj) || PyUnicode_Check(obj))) {
  1132. PyObject *tmp = PySequence_GetItem(obj,0);
  1133. if (tmp) {
  1134. if (complex_double_from_pyobj(v,tmp,errmess)) {
  1135. Py_DECREF(tmp);
  1136. return 1;
  1137. }
  1138. Py_DECREF(tmp);
  1139. }
  1140. }
  1141. {
  1142. PyObject* err = PyErr_Occurred();
  1143. if (err==NULL)
  1144. err = PyExc_TypeError;
  1145. PyErr_SetString(err,errmess);
  1146. }
  1147. return 0;
  1148. }
  1149. """
  1150. needs['complex_float_from_pyobj'] = [
  1151. 'complex_float', 'complex_double_from_pyobj']
  1152. cfuncs['complex_float_from_pyobj'] = """
  1153. static int
  1154. complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess)
  1155. {
  1156. complex_double cd={0.0,0.0};
  1157. if (complex_double_from_pyobj(&cd,obj,errmess)) {
  1158. (*v).r = (float)cd.r;
  1159. (*v).i = (float)cd.i;
  1160. return 1;
  1161. }
  1162. return 0;
  1163. }
  1164. """
  1165. cfuncs['try_pyarr_from_character'] = """
  1166. static int try_pyarr_from_character(PyObject* obj, character* v) {
  1167. PyArrayObject *arr = (PyArrayObject*)obj;
  1168. if (!obj) return -2;
  1169. if (PyArray_Check(obj)) {
  1170. if (F2PY_ARRAY_IS_CHARACTER_COMPATIBLE(arr)) {
  1171. *(character *)(PyArray_DATA(arr)) = *v;
  1172. return 1;
  1173. }
  1174. }
  1175. {
  1176. char mess[F2PY_MESSAGE_BUFFER_SIZE];
  1177. PyObject* err = PyErr_Occurred();
  1178. if (err == NULL) {
  1179. err = PyExc_ValueError;
  1180. strcpy(mess, "try_pyarr_from_character failed"
  1181. " -- expected bytes array-scalar|array, got ");
  1182. f2py_describe(obj, mess + strlen(mess));
  1183. PyErr_SetString(err, mess);
  1184. }
  1185. }
  1186. return 0;
  1187. }
  1188. """
  1189. needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE']
  1190. cfuncs[
  1191. 'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,\'c\');\n}\n'
  1192. needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char']
  1193. cfuncs[
  1194. 'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n'
  1195. needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char']
  1196. cfuncs[
  1197. 'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n'
  1198. needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE']
  1199. cfuncs[
  1200. 'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,\'s\');\n}\n'
  1201. needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE']
  1202. cfuncs[
  1203. 'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,\'i\');\n}\n'
  1204. needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE']
  1205. cfuncs[
  1206. 'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,\'l\');\n}\n'
  1207. needs['try_pyarr_from_long_long'] = [
  1208. 'pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long']
  1209. cfuncs[
  1210. 'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n'
  1211. needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE']
  1212. cfuncs[
  1213. 'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,\'f\');\n}\n'
  1214. needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE']
  1215. cfuncs[
  1216. 'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,\'d\');\n}\n'
  1217. needs['try_pyarr_from_complex_float'] = [
  1218. 'pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float']
  1219. cfuncs[
  1220. 'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n'
  1221. needs['try_pyarr_from_complex_double'] = [
  1222. 'pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double']
  1223. cfuncs[
  1224. 'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n'
  1225. needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX']
  1226. # create the list of arguments to be used when calling back to python
  1227. cfuncs['create_cb_arglist'] = """
  1228. static int
  1229. create_cb_arglist(PyObject* fun, PyTupleObject* xa , const int maxnofargs,
  1230. const int nofoptargs, int *nofargs, PyTupleObject **args,
  1231. const char *errmess)
  1232. {
  1233. PyObject *tmp = NULL;
  1234. PyObject *tmp_fun = NULL;
  1235. Py_ssize_t tot, opt, ext, siz, i, di = 0;
  1236. CFUNCSMESS(\"create_cb_arglist\\n\");
  1237. tot=opt=ext=siz=0;
  1238. /* Get the total number of arguments */
  1239. if (PyFunction_Check(fun)) {
  1240. tmp_fun = fun;
  1241. Py_INCREF(tmp_fun);
  1242. }
  1243. else {
  1244. di = 1;
  1245. if (PyObject_HasAttrString(fun,\"im_func\")) {
  1246. tmp_fun = PyObject_GetAttrString(fun,\"im_func\");
  1247. }
  1248. else if (PyObject_HasAttrString(fun,\"__call__\")) {
  1249. tmp = PyObject_GetAttrString(fun,\"__call__\");
  1250. if (PyObject_HasAttrString(tmp,\"im_func\"))
  1251. tmp_fun = PyObject_GetAttrString(tmp,\"im_func\");
  1252. else {
  1253. tmp_fun = fun; /* built-in function */
  1254. Py_INCREF(tmp_fun);
  1255. tot = maxnofargs;
  1256. if (PyCFunction_Check(fun)) {
  1257. /* In case the function has a co_argcount (like on PyPy) */
  1258. di = 0;
  1259. }
  1260. if (xa != NULL)
  1261. tot += PyTuple_Size((PyObject *)xa);
  1262. }
  1263. Py_XDECREF(tmp);
  1264. }
  1265. else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) {
  1266. tot = maxnofargs;
  1267. if (xa != NULL)
  1268. tot += PyTuple_Size((PyObject *)xa);
  1269. tmp_fun = fun;
  1270. Py_INCREF(tmp_fun);
  1271. }
  1272. else if (F2PyCapsule_Check(fun)) {
  1273. tot = maxnofargs;
  1274. if (xa != NULL)
  1275. ext = PyTuple_Size((PyObject *)xa);
  1276. if(ext>0) {
  1277. fprintf(stderr,\"extra arguments tuple cannot be used with PyCapsule call-back\\n\");
  1278. goto capi_fail;
  1279. }
  1280. tmp_fun = fun;
  1281. Py_INCREF(tmp_fun);
  1282. }
  1283. }
  1284. if (tmp_fun == NULL) {
  1285. fprintf(stderr,
  1286. \"Call-back argument must be function|instance|instance.__call__|f2py-function \"
  1287. \"but got %s.\\n\",
  1288. ((fun == NULL) ? \"NULL\" : Py_TYPE(fun)->tp_name));
  1289. goto capi_fail;
  1290. }
  1291. if (PyObject_HasAttrString(tmp_fun,\"__code__\")) {
  1292. if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) {
  1293. PyObject *tmp_argcount = PyObject_GetAttrString(tmp,\"co_argcount\");
  1294. Py_DECREF(tmp);
  1295. if (tmp_argcount == NULL) {
  1296. goto capi_fail;
  1297. }
  1298. tot = PyLong_AsSsize_t(tmp_argcount) - di;
  1299. Py_DECREF(tmp_argcount);
  1300. }
  1301. }
  1302. /* Get the number of optional arguments */
  1303. if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) {
  1304. if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\")))
  1305. opt = PyTuple_Size(tmp);
  1306. Py_XDECREF(tmp);
  1307. }
  1308. /* Get the number of extra arguments */
  1309. if (xa != NULL)
  1310. ext = PyTuple_Size((PyObject *)xa);
  1311. /* Calculate the size of call-backs argument list */
  1312. siz = MIN(maxnofargs+ext,tot);
  1313. *nofargs = MAX(0,siz-ext);
  1314. #ifdef DEBUGCFUNCS
  1315. fprintf(stderr,
  1316. \"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),\"
  1317. \"tot,opt,ext,siz,nofargs = %d(-%d), %zd, %zd, %zd, %zd, %d\\n\",
  1318. maxnofargs, nofoptargs, tot, opt, ext, siz, *nofargs);
  1319. #endif
  1320. if (siz < tot-opt) {
  1321. fprintf(stderr,
  1322. \"create_cb_arglist: Failed to build argument list \"
  1323. \"(siz) with enough arguments (tot-opt) required by \"
  1324. \"user-supplied function (siz,tot,opt=%zd, %zd, %zd).\\n\",
  1325. siz, tot, opt);
  1326. goto capi_fail;
  1327. }
  1328. /* Initialize argument list */
  1329. *args = (PyTupleObject *)PyTuple_New(siz);
  1330. for (i=0;i<*nofargs;i++) {
  1331. Py_INCREF(Py_None);
  1332. PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None);
  1333. }
  1334. if (xa != NULL)
  1335. for (i=(*nofargs);i<siz;i++) {
  1336. tmp = PyTuple_GetItem((PyObject *)xa,i-(*nofargs));
  1337. Py_INCREF(tmp);
  1338. PyTuple_SET_ITEM(*args,i,tmp);
  1339. }
  1340. CFUNCSMESS(\"create_cb_arglist-end\\n\");
  1341. Py_DECREF(tmp_fun);
  1342. return 1;
  1343. capi_fail:
  1344. if (PyErr_Occurred() == NULL)
  1345. PyErr_SetString(#modulename#_error, errmess);
  1346. Py_XDECREF(tmp_fun);
  1347. return 0;
  1348. }
  1349. """
  1350. def buildcfuncs():
  1351. from .capi_maps import c2capi_map
  1352. for k in c2capi_map.keys():
  1353. m = 'pyarr_from_p_%s1' % k
  1354. cppmacros[
  1355. m] = '#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))' % (m, c2capi_map[k])
  1356. k = 'string'
  1357. m = 'pyarr_from_p_%s1' % k
  1358. # NPY_CHAR compatibility, NPY_STRING with itemsize 1
  1359. cppmacros[
  1360. m] = '#define %s(v,dims) (PyArray_New(&PyArray_Type, 1, dims, NPY_STRING, NULL, v, 1, NPY_ARRAY_CARRAY, NULL))' % (m)
  1361. ############ Auxiliary functions for sorting needs ###################
  1362. def append_needs(need, flag=1):
  1363. # This function modifies the contents of the global `outneeds` dict.
  1364. if isinstance(need, list):
  1365. for n in need:
  1366. append_needs(n, flag)
  1367. elif isinstance(need, str):
  1368. if not need:
  1369. return
  1370. if need in includes0:
  1371. n = 'includes0'
  1372. elif need in includes:
  1373. n = 'includes'
  1374. elif need in typedefs:
  1375. n = 'typedefs'
  1376. elif need in typedefs_generated:
  1377. n = 'typedefs_generated'
  1378. elif need in cppmacros:
  1379. n = 'cppmacros'
  1380. elif need in cfuncs:
  1381. n = 'cfuncs'
  1382. elif need in callbacks:
  1383. n = 'callbacks'
  1384. elif need in f90modhooks:
  1385. n = 'f90modhooks'
  1386. elif need in commonhooks:
  1387. n = 'commonhooks'
  1388. else:
  1389. errmess('append_needs: unknown need %s\n' % (repr(need)))
  1390. return
  1391. if need in outneeds[n]:
  1392. return
  1393. if flag:
  1394. tmp = {}
  1395. if need in needs:
  1396. for nn in needs[need]:
  1397. t = append_needs(nn, 0)
  1398. if isinstance(t, dict):
  1399. for nnn in t.keys():
  1400. if nnn in tmp:
  1401. tmp[nnn] = tmp[nnn] + t[nnn]
  1402. else:
  1403. tmp[nnn] = t[nnn]
  1404. for nn in tmp.keys():
  1405. for nnn in tmp[nn]:
  1406. if nnn not in outneeds[nn]:
  1407. outneeds[nn] = [nnn] + outneeds[nn]
  1408. outneeds[n].append(need)
  1409. else:
  1410. tmp = {}
  1411. if need in needs:
  1412. for nn in needs[need]:
  1413. t = append_needs(nn, flag)
  1414. if isinstance(t, dict):
  1415. for nnn in t.keys():
  1416. if nnn in tmp:
  1417. tmp[nnn] = t[nnn] + tmp[nnn]
  1418. else:
  1419. tmp[nnn] = t[nnn]
  1420. if n not in tmp:
  1421. tmp[n] = []
  1422. tmp[n].append(need)
  1423. return tmp
  1424. else:
  1425. errmess('append_needs: expected list or string but got :%s\n' %
  1426. (repr(need)))
  1427. def get_needs():
  1428. # This function modifies the contents of the global `outneeds` dict.
  1429. res = {}
  1430. for n in outneeds.keys():
  1431. out = []
  1432. saveout = copy.copy(outneeds[n])
  1433. while len(outneeds[n]) > 0:
  1434. if outneeds[n][0] not in needs:
  1435. out.append(outneeds[n][0])
  1436. del outneeds[n][0]
  1437. else:
  1438. flag = 0
  1439. for k in outneeds[n][1:]:
  1440. if k in needs[outneeds[n][0]]:
  1441. flag = 1
  1442. break
  1443. if flag:
  1444. outneeds[n] = outneeds[n][1:] + [outneeds[n][0]]
  1445. else:
  1446. out.append(outneeds[n][0])
  1447. del outneeds[n][0]
  1448. if saveout and (0 not in map(lambda x, y: x == y, saveout, outneeds[n])) \
  1449. and outneeds[n] != []:
  1450. print(n, saveout)
  1451. errmess(
  1452. 'get_needs: no progress in sorting needs, probably circular dependence, skipping.\n')
  1453. out = out + saveout
  1454. break
  1455. saveout = copy.copy(outneeds[n])
  1456. if out == []:
  1457. out = [n]
  1458. res[n] = out
  1459. return res