auxfuncs.py 26 KB

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