auxfuncs.py 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. """
  2. Auxiliary functions for f2py2e.
  3. Copyright 1999 -- 2011 Pearu Peterson all rights reserved.
  4. Copyright 2011 -- present NumPy Developers.
  5. Permission to use, modify, and distribute this software is given under the
  6. terms of the NumPy (BSD style) LICENSE.
  7. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  8. """
  9. import pprint
  10. import sys
  11. import re
  12. import types
  13. from functools import reduce
  14. from . import __version__
  15. from . import cfuncs
  16. from .cfuncs import errmess
  17. __all__ = [
  18. 'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle',
  19. 'getargs2', 'getcallprotoargument', 'getcallstatement',
  20. 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode',
  21. 'getusercode1', 'getdimension', 'hasbody', 'hascallstatement', 'hascommon',
  22. 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote',
  23. 'isallocatable', 'isarray', 'isarrayofstrings',
  24. 'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray',
  25. 'iscomplex', 'iscstyledirective',
  26. 'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn',
  27. 'isdouble', 'isdummyroutine', 'isexternal', 'isfunction',
  28. 'isfunction_wrap', 'isint1', 'isint1array', 'isinteger', 'isintent_aux',
  29. 'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict',
  30. 'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace',
  31. 'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical',
  32. 'islogicalfunction', 'islong_complex', 'islong_double',
  33. 'islong_doublefunction', 'islong_long', 'islong_longfunction',
  34. 'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isvariable',
  35. 'isrequired', 'isroutine', 'isscalar', 'issigned_long_longarray',
  36. 'isstring', 'isstringarray', 'isstring_or_stringarray', 'isstringfunction',
  37. 'issubroutine', 'get_f2py_modulename', 'issubroutine_wrap', 'isthreadsafe',
  38. 'isunsigned', 'isunsigned_char', 'isunsigned_chararray',
  39. 'isunsigned_long_long', 'isunsigned_long_longarray', 'isunsigned_short',
  40. 'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess', 'replace',
  41. 'show', 'stripcomma', 'throw_error', 'isattr_value', 'getuseblocks',
  42. 'process_f2cmap_dict', 'containscommon'
  43. ]
  44. f2py_version = __version__.version
  45. show = pprint.pprint
  46. options = {}
  47. debugoptions = []
  48. wrapfuncs = 1
  49. def outmess(t):
  50. if options.get('verbose', 1):
  51. sys.stdout.write(t)
  52. def debugcapi(var):
  53. return 'capi' in debugoptions
  54. def _ischaracter(var):
  55. return 'typespec' in var and var['typespec'] == 'character' and \
  56. not isexternal(var)
  57. def _isstring(var):
  58. return 'typespec' in var and var['typespec'] == 'character' and \
  59. not isexternal(var)
  60. def ischaracter_or_characterarray(var):
  61. return _ischaracter(var) and 'charselector' not in var
  62. def ischaracter(var):
  63. return ischaracter_or_characterarray(var) and not isarray(var)
  64. def ischaracterarray(var):
  65. return ischaracter_or_characterarray(var) and isarray(var)
  66. def isstring_or_stringarray(var):
  67. return _ischaracter(var) and 'charselector' in var
  68. def isstring(var):
  69. return isstring_or_stringarray(var) and not isarray(var)
  70. def isstringarray(var):
  71. return isstring_or_stringarray(var) and isarray(var)
  72. def isarrayofstrings(var): # obsolete?
  73. # leaving out '*' for now so that `character*(*) a(m)` and `character
  74. # a(m,*)` are treated differently. Luckily `character**` is illegal.
  75. return isstringarray(var) and var['dimension'][-1] == '(*)'
  76. def isarray(var):
  77. return 'dimension' in var and not isexternal(var)
  78. def isscalar(var):
  79. return not (isarray(var) or isstring(var) or isexternal(var))
  80. def iscomplex(var):
  81. return isscalar(var) and \
  82. var.get('typespec') in ['complex', 'double complex']
  83. def islogical(var):
  84. return isscalar(var) and var.get('typespec') == 'logical'
  85. def isinteger(var):
  86. return isscalar(var) and var.get('typespec') == 'integer'
  87. def isreal(var):
  88. return isscalar(var) and var.get('typespec') == 'real'
  89. def get_kind(var):
  90. try:
  91. return var['kindselector']['*']
  92. except KeyError:
  93. try:
  94. return var['kindselector']['kind']
  95. except KeyError:
  96. pass
  97. def isint1(var):
  98. return var.get('typespec') == 'integer' \
  99. and get_kind(var) == '1' and not isarray(var)
  100. def islong_long(var):
  101. if not isscalar(var):
  102. return 0
  103. if var.get('typespec') not in ['integer', 'logical']:
  104. return 0
  105. return get_kind(var) == '8'
  106. def isunsigned_char(var):
  107. if not isscalar(var):
  108. return 0
  109. if var.get('typespec') != 'integer':
  110. return 0
  111. return get_kind(var) == '-1'
  112. def isunsigned_short(var):
  113. if not isscalar(var):
  114. return 0
  115. if var.get('typespec') != 'integer':
  116. return 0
  117. return get_kind(var) == '-2'
  118. def isunsigned(var):
  119. if not isscalar(var):
  120. return 0
  121. if var.get('typespec') != 'integer':
  122. return 0
  123. return get_kind(var) == '-4'
  124. def isunsigned_long_long(var):
  125. if not isscalar(var):
  126. return 0
  127. if var.get('typespec') != 'integer':
  128. return 0
  129. return get_kind(var) == '-8'
  130. def isdouble(var):
  131. if not isscalar(var):
  132. return 0
  133. if not var.get('typespec') == 'real':
  134. return 0
  135. return get_kind(var) == '8'
  136. def islong_double(var):
  137. if not isscalar(var):
  138. return 0
  139. if not var.get('typespec') == 'real':
  140. return 0
  141. return get_kind(var) == '16'
  142. def islong_complex(var):
  143. if not iscomplex(var):
  144. return 0
  145. return get_kind(var) == '32'
  146. def iscomplexarray(var):
  147. return isarray(var) and \
  148. var.get('typespec') in ['complex', 'double complex']
  149. def isint1array(var):
  150. return isarray(var) and var.get('typespec') == 'integer' \
  151. and get_kind(var) == '1'
  152. def isunsigned_chararray(var):
  153. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  154. and get_kind(var) == '-1'
  155. def isunsigned_shortarray(var):
  156. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  157. and get_kind(var) == '-2'
  158. def isunsignedarray(var):
  159. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  160. and get_kind(var) == '-4'
  161. def isunsigned_long_longarray(var):
  162. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  163. and get_kind(var) == '-8'
  164. def issigned_chararray(var):
  165. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  166. and get_kind(var) == '1'
  167. def issigned_shortarray(var):
  168. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  169. and get_kind(var) == '2'
  170. def issigned_array(var):
  171. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  172. and get_kind(var) == '4'
  173. def issigned_long_longarray(var):
  174. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  175. and get_kind(var) == '8'
  176. def isallocatable(var):
  177. return 'attrspec' in var and 'allocatable' in var['attrspec']
  178. def ismutable(var):
  179. return not ('dimension' not in var or isstring(var))
  180. def ismoduleroutine(rout):
  181. return 'modulename' in rout
  182. def ismodule(rout):
  183. return 'block' in rout and 'module' == rout['block']
  184. def isfunction(rout):
  185. return 'block' in rout and 'function' == rout['block']
  186. def isfunction_wrap(rout):
  187. if isintent_c(rout):
  188. return 0
  189. return wrapfuncs and isfunction(rout) and (not isexternal(rout))
  190. def issubroutine(rout):
  191. return 'block' in rout and 'subroutine' == rout['block']
  192. def issubroutine_wrap(rout):
  193. if isintent_c(rout):
  194. return 0
  195. return issubroutine(rout) and hasassumedshape(rout)
  196. def isattr_value(var):
  197. return 'value' in var.get('attrspec', [])
  198. def hasassumedshape(rout):
  199. if rout.get('hasassumedshape'):
  200. return True
  201. for a in rout['args']:
  202. for d in rout['vars'].get(a, {}).get('dimension', []):
  203. if d == ':':
  204. rout['hasassumedshape'] = True
  205. return True
  206. return False
  207. def requiresf90wrapper(rout):
  208. return ismoduleroutine(rout) or hasassumedshape(rout)
  209. def isroutine(rout):
  210. return isfunction(rout) or issubroutine(rout)
  211. def islogicalfunction(rout):
  212. if not isfunction(rout):
  213. return 0
  214. if 'result' in rout:
  215. a = rout['result']
  216. else:
  217. a = rout['name']
  218. if a in rout['vars']:
  219. return islogical(rout['vars'][a])
  220. return 0
  221. def islong_longfunction(rout):
  222. if not isfunction(rout):
  223. return 0
  224. if 'result' in rout:
  225. a = rout['result']
  226. else:
  227. a = rout['name']
  228. if a in rout['vars']:
  229. return islong_long(rout['vars'][a])
  230. return 0
  231. def islong_doublefunction(rout):
  232. if not isfunction(rout):
  233. return 0
  234. if 'result' in rout:
  235. a = rout['result']
  236. else:
  237. a = rout['name']
  238. if a in rout['vars']:
  239. return islong_double(rout['vars'][a])
  240. return 0
  241. def iscomplexfunction(rout):
  242. if not isfunction(rout):
  243. return 0
  244. if 'result' in rout:
  245. a = rout['result']
  246. else:
  247. a = rout['name']
  248. if a in rout['vars']:
  249. return iscomplex(rout['vars'][a])
  250. return 0
  251. def iscomplexfunction_warn(rout):
  252. if iscomplexfunction(rout):
  253. outmess("""\
  254. **************************************************************
  255. Warning: code with a function returning complex value
  256. may not work correctly with your Fortran compiler.
  257. When using GNU gcc/g77 compilers, codes should work
  258. correctly for callbacks with:
  259. f2py -c -DF2PY_CB_RETURNCOMPLEX
  260. **************************************************************\n""")
  261. return 1
  262. return 0
  263. def isstringfunction(rout):
  264. if not isfunction(rout):
  265. return 0
  266. if 'result' in rout:
  267. a = rout['result']
  268. else:
  269. a = rout['name']
  270. if a in rout['vars']:
  271. return isstring(rout['vars'][a])
  272. return 0
  273. def hasexternals(rout):
  274. return 'externals' in rout and rout['externals']
  275. def isthreadsafe(rout):
  276. return 'f2pyenhancements' in rout and \
  277. 'threadsafe' in rout['f2pyenhancements']
  278. def hasvariables(rout):
  279. return 'vars' in rout and rout['vars']
  280. def isoptional(var):
  281. return ('attrspec' in var and 'optional' in var['attrspec'] and
  282. 'required' not in var['attrspec']) and isintent_nothide(var)
  283. def isexternal(var):
  284. return 'attrspec' in var and 'external' in var['attrspec']
  285. def getdimension(var):
  286. dimpattern = r"\((.*?)\)"
  287. if 'attrspec' in var.keys():
  288. if any('dimension' in s for s in var['attrspec']):
  289. return [re.findall(dimpattern, v) for v in var['attrspec']][0]
  290. def isrequired(var):
  291. return not isoptional(var) and isintent_nothide(var)
  292. def iscstyledirective(f2py_line):
  293. directives = {"callstatement", "callprotoargument", "pymethoddef"}
  294. return any(directive in f2py_line.lower() for directive in directives)
  295. def isintent_in(var):
  296. if 'intent' not in var:
  297. return 1
  298. if 'hide' in var['intent']:
  299. return 0
  300. if 'inplace' in var['intent']:
  301. return 0
  302. if 'in' in var['intent']:
  303. return 1
  304. if 'out' in var['intent']:
  305. return 0
  306. if 'inout' in var['intent']:
  307. return 0
  308. if 'outin' in var['intent']:
  309. return 0
  310. return 1
  311. def isintent_inout(var):
  312. return ('intent' in var and ('inout' in var['intent'] or
  313. 'outin' in var['intent']) and 'in' not in var['intent'] and
  314. 'hide' not in var['intent'] and 'inplace' not in var['intent'])
  315. def isintent_out(var):
  316. return 'out' in var.get('intent', [])
  317. def isintent_hide(var):
  318. return ('intent' in var and ('hide' in var['intent'] or
  319. ('out' in var['intent'] and 'in' not in var['intent'] and
  320. (not l_or(isintent_inout, isintent_inplace)(var)))))
  321. def isintent_nothide(var):
  322. return not isintent_hide(var)
  323. def isintent_c(var):
  324. return 'c' in var.get('intent', [])
  325. def isintent_cache(var):
  326. return 'cache' in var.get('intent', [])
  327. def isintent_copy(var):
  328. return 'copy' in var.get('intent', [])
  329. def isintent_overwrite(var):
  330. return 'overwrite' in var.get('intent', [])
  331. def isintent_callback(var):
  332. return 'callback' in var.get('intent', [])
  333. def isintent_inplace(var):
  334. return 'inplace' in var.get('intent', [])
  335. def isintent_aux(var):
  336. return 'aux' in var.get('intent', [])
  337. def isintent_aligned4(var):
  338. return 'aligned4' in var.get('intent', [])
  339. def isintent_aligned8(var):
  340. return 'aligned8' in var.get('intent', [])
  341. def isintent_aligned16(var):
  342. return 'aligned16' in var.get('intent', [])
  343. isintent_dict = {isintent_in: 'INTENT_IN', isintent_inout: 'INTENT_INOUT',
  344. isintent_out: 'INTENT_OUT', isintent_hide: 'INTENT_HIDE',
  345. isintent_cache: 'INTENT_CACHE',
  346. isintent_c: 'INTENT_C', isoptional: 'OPTIONAL',
  347. isintent_inplace: 'INTENT_INPLACE',
  348. isintent_aligned4: 'INTENT_ALIGNED4',
  349. isintent_aligned8: 'INTENT_ALIGNED8',
  350. isintent_aligned16: 'INTENT_ALIGNED16',
  351. }
  352. def isprivate(var):
  353. return 'attrspec' in var and 'private' in var['attrspec']
  354. def isvariable(var):
  355. # heuristic to find public/private declarations of filtered subroutines
  356. if len(var) == 1 and 'attrspec' in var and \
  357. var['attrspec'][0] in ('public', 'private'):
  358. is_var = False
  359. else:
  360. is_var = True
  361. return is_var
  362. def hasinitvalue(var):
  363. return '=' in var
  364. def hasinitvalueasstring(var):
  365. if not hasinitvalue(var):
  366. return 0
  367. return var['='][0] in ['"', "'"]
  368. def hasnote(var):
  369. return 'note' in var
  370. def hasresultnote(rout):
  371. if not isfunction(rout):
  372. return 0
  373. if 'result' in rout:
  374. a = rout['result']
  375. else:
  376. a = rout['name']
  377. if a in rout['vars']:
  378. return hasnote(rout['vars'][a])
  379. return 0
  380. def hascommon(rout):
  381. return 'common' in rout
  382. def containscommon(rout):
  383. if hascommon(rout):
  384. return 1
  385. if hasbody(rout):
  386. for b in rout['body']:
  387. if containscommon(b):
  388. return 1
  389. return 0
  390. def containsmodule(block):
  391. if ismodule(block):
  392. return 1
  393. if not hasbody(block):
  394. return 0
  395. for b in block['body']:
  396. if containsmodule(b):
  397. return 1
  398. return 0
  399. def hasbody(rout):
  400. return 'body' in rout
  401. def hascallstatement(rout):
  402. return getcallstatement(rout) is not None
  403. def istrue(var):
  404. return 1
  405. def isfalse(var):
  406. return 0
  407. class F2PYError(Exception):
  408. pass
  409. class throw_error:
  410. def __init__(self, mess):
  411. self.mess = mess
  412. def __call__(self, var):
  413. mess = '\n\n var = %s\n Message: %s\n' % (var, self.mess)
  414. raise F2PYError(mess)
  415. def l_and(*f):
  416. l1, l2 = 'lambda v', []
  417. for i in range(len(f)):
  418. l1 = '%s,f%d=f[%d]' % (l1, i, i)
  419. l2.append('f%d(v)' % (i))
  420. return eval('%s:%s' % (l1, ' and '.join(l2)))
  421. def l_or(*f):
  422. l1, l2 = 'lambda v', []
  423. for i in range(len(f)):
  424. l1 = '%s,f%d=f[%d]' % (l1, i, i)
  425. l2.append('f%d(v)' % (i))
  426. return eval('%s:%s' % (l1, ' or '.join(l2)))
  427. def l_not(f):
  428. return eval('lambda v,f=f:not f(v)')
  429. def isdummyroutine(rout):
  430. try:
  431. return rout['f2pyenhancements']['fortranname'] == ''
  432. except KeyError:
  433. return 0
  434. def getfortranname(rout):
  435. try:
  436. name = rout['f2pyenhancements']['fortranname']
  437. if name == '':
  438. raise KeyError
  439. if not name:
  440. errmess('Failed to use fortranname from %s\n' %
  441. (rout['f2pyenhancements']))
  442. raise KeyError
  443. except KeyError:
  444. name = rout['name']
  445. return name
  446. def getmultilineblock(rout, blockname, comment=1, counter=0):
  447. try:
  448. r = rout['f2pyenhancements'].get(blockname)
  449. except KeyError:
  450. return
  451. if not r:
  452. return
  453. if counter > 0 and isinstance(r, str):
  454. return
  455. if isinstance(r, list):
  456. if counter >= len(r):
  457. return
  458. r = r[counter]
  459. if r[:3] == "'''":
  460. if comment:
  461. r = '\t/* start ' + blockname + \
  462. ' multiline (' + repr(counter) + ') */\n' + r[3:]
  463. else:
  464. r = r[3:]
  465. if r[-3:] == "'''":
  466. if comment:
  467. r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/'
  468. else:
  469. r = r[:-3]
  470. else:
  471. errmess("%s multiline block should end with `'''`: %s\n"
  472. % (blockname, repr(r)))
  473. return r
  474. def getcallstatement(rout):
  475. return getmultilineblock(rout, 'callstatement')
  476. def getcallprotoargument(rout, cb_map={}):
  477. r = getmultilineblock(rout, 'callprotoargument', comment=0)
  478. if r:
  479. return r
  480. if hascallstatement(rout):
  481. outmess(
  482. 'warning: callstatement is defined without callprotoargument\n')
  483. return
  484. from .capi_maps import getctype
  485. arg_types, arg_types2 = [], []
  486. if l_and(isstringfunction, l_not(isfunction_wrap))(rout):
  487. arg_types.extend(['char*', 'size_t'])
  488. for n in rout['args']:
  489. var = rout['vars'][n]
  490. if isintent_callback(var):
  491. continue
  492. if n in cb_map:
  493. ctype = cb_map[n] + '_typedef'
  494. else:
  495. ctype = getctype(var)
  496. if l_and(isintent_c, l_or(isscalar, iscomplex))(var):
  497. pass
  498. elif isstring(var):
  499. pass
  500. else:
  501. if not isattr_value(var):
  502. ctype = ctype + '*'
  503. if (isstring(var)
  504. or isarrayofstrings(var) # obsolete?
  505. or isstringarray(var)):
  506. arg_types2.append('size_t')
  507. arg_types.append(ctype)
  508. proto_args = ','.join(arg_types + arg_types2)
  509. if not proto_args:
  510. proto_args = 'void'
  511. return proto_args
  512. def getusercode(rout):
  513. return getmultilineblock(rout, 'usercode')
  514. def getusercode1(rout):
  515. return getmultilineblock(rout, 'usercode', counter=1)
  516. def getpymethoddef(rout):
  517. return getmultilineblock(rout, 'pymethoddef')
  518. def getargs(rout):
  519. sortargs, args = [], []
  520. if 'args' in rout:
  521. args = rout['args']
  522. if 'sortvars' in rout:
  523. for a in rout['sortvars']:
  524. if a in args:
  525. sortargs.append(a)
  526. for a in args:
  527. if a not in sortargs:
  528. sortargs.append(a)
  529. else:
  530. sortargs = rout['args']
  531. return args, sortargs
  532. def getargs2(rout):
  533. sortargs, args = [], rout.get('args', [])
  534. auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a])
  535. and a not in args]
  536. args = auxvars + args
  537. if 'sortvars' in rout:
  538. for a in rout['sortvars']:
  539. if a in args:
  540. sortargs.append(a)
  541. for a in args:
  542. if a not in sortargs:
  543. sortargs.append(a)
  544. else:
  545. sortargs = auxvars + rout['args']
  546. return args, sortargs
  547. def getrestdoc(rout):
  548. if 'f2pymultilines' not in rout:
  549. return None
  550. k = None
  551. if rout['block'] == 'python module':
  552. k = rout['block'], rout['name']
  553. return rout['f2pymultilines'].get(k, None)
  554. def gentitle(name):
  555. ln = (80 - len(name) - 6) // 2
  556. return '/*%s %s %s*/' % (ln * '*', name, ln * '*')
  557. def flatlist(lst):
  558. if isinstance(lst, list):
  559. return reduce(lambda x, y, f=flatlist: x + f(y), lst, [])
  560. return [lst]
  561. def stripcomma(s):
  562. if s and s[-1] == ',':
  563. return s[:-1]
  564. return s
  565. def replace(str, d, defaultsep=''):
  566. if isinstance(d, list):
  567. return [replace(str, _m, defaultsep) for _m in d]
  568. if isinstance(str, list):
  569. return [replace(_m, d, defaultsep) for _m in str]
  570. for k in 2 * list(d.keys()):
  571. if k == 'separatorsfor':
  572. continue
  573. if 'separatorsfor' in d and k in d['separatorsfor']:
  574. sep = d['separatorsfor'][k]
  575. else:
  576. sep = defaultsep
  577. if isinstance(d[k], list):
  578. str = str.replace('#%s#' % (k), sep.join(flatlist(d[k])))
  579. else:
  580. str = str.replace('#%s#' % (k), d[k])
  581. return str
  582. def dictappend(rd, ar):
  583. if isinstance(ar, list):
  584. for a in ar:
  585. rd = dictappend(rd, a)
  586. return rd
  587. for k in ar.keys():
  588. if k[0] == '_':
  589. continue
  590. if k in rd:
  591. if isinstance(rd[k], str):
  592. rd[k] = [rd[k]]
  593. if isinstance(rd[k], list):
  594. if isinstance(ar[k], list):
  595. rd[k] = rd[k] + ar[k]
  596. else:
  597. rd[k].append(ar[k])
  598. elif isinstance(rd[k], dict):
  599. if isinstance(ar[k], dict):
  600. if k == 'separatorsfor':
  601. for k1 in ar[k].keys():
  602. if k1 not in rd[k]:
  603. rd[k][k1] = ar[k][k1]
  604. else:
  605. rd[k] = dictappend(rd[k], ar[k])
  606. else:
  607. rd[k] = ar[k]
  608. return rd
  609. def applyrules(rules, d, var={}):
  610. ret = {}
  611. if isinstance(rules, list):
  612. for r in rules:
  613. rr = applyrules(r, d, var)
  614. ret = dictappend(ret, rr)
  615. if '_break' in rr:
  616. break
  617. return ret
  618. if '_check' in rules and (not rules['_check'](var)):
  619. return ret
  620. if 'need' in rules:
  621. res = applyrules({'needs': rules['need']}, d, var)
  622. if 'needs' in res:
  623. cfuncs.append_needs(res['needs'])
  624. for k in rules.keys():
  625. if k == 'separatorsfor':
  626. ret[k] = rules[k]
  627. continue
  628. if isinstance(rules[k], str):
  629. ret[k] = replace(rules[k], d)
  630. elif isinstance(rules[k], list):
  631. ret[k] = []
  632. for i in rules[k]:
  633. ar = applyrules({k: i}, d, var)
  634. if k in ar:
  635. ret[k].append(ar[k])
  636. elif k[0] == '_':
  637. continue
  638. elif isinstance(rules[k], dict):
  639. ret[k] = []
  640. for k1 in rules[k].keys():
  641. if isinstance(k1, types.FunctionType) and k1(var):
  642. if isinstance(rules[k][k1], list):
  643. for i in rules[k][k1]:
  644. if isinstance(i, dict):
  645. res = applyrules({'supertext': i}, d, var)
  646. if 'supertext' in res:
  647. i = res['supertext']
  648. else:
  649. i = ''
  650. ret[k].append(replace(i, d))
  651. else:
  652. i = rules[k][k1]
  653. if isinstance(i, dict):
  654. res = applyrules({'supertext': i}, d)
  655. if 'supertext' in res:
  656. i = res['supertext']
  657. else:
  658. i = ''
  659. ret[k].append(replace(i, d))
  660. else:
  661. errmess('applyrules: ignoring rule %s.\n' % repr(rules[k]))
  662. if isinstance(ret[k], list):
  663. if len(ret[k]) == 1:
  664. ret[k] = ret[k][0]
  665. if ret[k] == []:
  666. del ret[k]
  667. return ret
  668. _f2py_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]+)',
  669. re.I).match
  670. _f2py_user_module_name_match = re.compile(r'\s*python\s*module\s*(?P<name>[\w_]*?'
  671. r'__user__[\w_]*)', re.I).match
  672. def get_f2py_modulename(source):
  673. name = None
  674. with open(source) as f:
  675. for line in f:
  676. m = _f2py_module_name_match(line)
  677. if m:
  678. if _f2py_user_module_name_match(line): # skip *__user__* names
  679. continue
  680. name = m.group('name')
  681. break
  682. return name
  683. def getuseblocks(pymod):
  684. all_uses = []
  685. for inner in pymod['body']:
  686. for modblock in inner['body']:
  687. if modblock.get('use'):
  688. all_uses.extend([x for x in modblock.get("use").keys() if "__" not in x])
  689. return all_uses
  690. def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose = False):
  691. """
  692. Update the Fortran-to-C type mapping dictionary with new mappings and
  693. return a list of successfully mapped C types.
  694. This function integrates a new mapping dictionary into an existing
  695. Fortran-to-C type mapping dictionary. It ensures that all keys are in
  696. lowercase and validates new entries against a given C-to-Python mapping
  697. dictionary. Redefinitions and invalid entries are reported with a warning.
  698. Parameters
  699. ----------
  700. f2cmap_all : dict
  701. The existing Fortran-to-C type mapping dictionary that will be updated.
  702. It should be a dictionary of dictionaries where the main keys represent
  703. Fortran types and the nested dictionaries map Fortran type specifiers
  704. to corresponding C types.
  705. new_map : dict
  706. A dictionary containing new type mappings to be added to `f2cmap_all`.
  707. The structure should be similar to `f2cmap_all`, with keys representing
  708. Fortran types and values being dictionaries of type specifiers and their
  709. C type equivalents.
  710. c2py_map : dict
  711. A dictionary used for validating the C types in `new_map`. It maps C
  712. types to corresponding Python types and is used to ensure that the C
  713. types specified in `new_map` are valid.
  714. verbose : boolean
  715. A flag used to provide information about the types mapped
  716. Returns
  717. -------
  718. tuple of (dict, list)
  719. The updated Fortran-to-C type mapping dictionary and a list of
  720. successfully mapped C types.
  721. """
  722. f2cmap_mapped = []
  723. new_map_lower = {}
  724. for k, d1 in new_map.items():
  725. d1_lower = {k1.lower(): v1 for k1, v1 in d1.items()}
  726. new_map_lower[k.lower()] = d1_lower
  727. for k, d1 in new_map_lower.items():
  728. if k not in f2cmap_all:
  729. f2cmap_all[k] = {}
  730. for k1, v1 in d1.items():
  731. if v1 in c2py_map:
  732. if k1 in f2cmap_all[k]:
  733. outmess(
  734. "\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n"
  735. % (k, k1, f2cmap_all[k][k1], v1)
  736. )
  737. f2cmap_all[k][k1] = v1
  738. if verbose:
  739. outmess('\tMapping "%s(kind=%s)" to "%s"\n' % (k, k1, v1))
  740. f2cmap_mapped.append(v1)
  741. else:
  742. if verbose:
  743. errmess(
  744. "\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"
  745. % (k, k1, v1, v1, list(c2py_map.keys()))
  746. )
  747. return f2cmap_all, f2cmap_mapped