cfuncs.py 50 KB

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