cfuncs.py 51 KB

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