auxfuncs.py 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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 re
  11. import sys
  12. import types
  13. from functools import reduce
  14. from . import __version__, cfuncs
  15. from .cfuncs import errmess
  16. __all__ = [
  17. 'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle',
  18. 'getargs2', 'getcallprotoargument', 'getcallstatement',
  19. 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode',
  20. 'getusercode1', 'getdimension', 'hasbody', 'hascallstatement', 'hascommon',
  21. 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote',
  22. 'isallocatable', 'isarray', 'isarrayofstrings',
  23. 'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray',
  24. 'iscomplex', 'iscstyledirective',
  25. 'iscomplexarray', 'iscomplexfunction', 'iscomplexfunction_warn',
  26. 'isdouble', 'isdummyroutine', 'isexternal', 'isfunction',
  27. 'isfunction_wrap', 'isint1', 'isint1array', 'isinteger', 'isintent_aux',
  28. 'isintent_c', 'isintent_callback', 'isintent_copy', 'isintent_dict',
  29. 'isintent_hide', 'isintent_in', 'isintent_inout', 'isintent_inplace',
  30. 'isintent_nothide', 'isintent_out', 'isintent_overwrite', 'islogical',
  31. 'islogicalfunction', 'islong_complex', 'islong_double',
  32. 'islong_doublefunction', 'islong_long', 'islong_longfunction',
  33. 'ismodule', 'ismoduleroutine', 'isoptional', 'isprivate', 'isvariable',
  34. 'isrequired', 'isroutine', 'isscalar', 'issigned_long_longarray',
  35. 'isstring', 'isstringarray', 'isstring_or_stringarray', 'isstringfunction',
  36. 'issubroutine', 'get_f2py_modulename', 'issubroutine_wrap', 'isthreadsafe',
  37. 'isunsigned', 'isunsigned_char', 'isunsigned_chararray',
  38. 'isunsigned_long_long', 'isunsigned_long_longarray', 'isunsigned_short',
  39. 'isunsigned_shortarray', 'l_and', 'l_not', 'l_or', 'outmess', 'replace',
  40. 'show', 'stripcomma', 'throw_error', 'isattr_value', 'getuseblocks',
  41. 'process_f2cmap_dict', 'containscommon', 'containsderivedtypes'
  42. ]
  43. f2py_version = __version__.version
  44. show = pprint.pprint
  45. options = {}
  46. debugoptions = []
  47. wrapfuncs = 1
  48. def outmess(t):
  49. if options.get('verbose', 1):
  50. sys.stdout.write(t)
  51. def debugcapi(var):
  52. return 'capi' in debugoptions
  53. def _ischaracter(var):
  54. return 'typespec' in var and var['typespec'] == 'character' and \
  55. not isexternal(var)
  56. def _isstring(var):
  57. return 'typespec' in var and var['typespec'] == 'character' and \
  58. not isexternal(var)
  59. def ischaracter_or_characterarray(var):
  60. return _ischaracter(var) and 'charselector' not in var
  61. def ischaracter(var):
  62. return ischaracter_or_characterarray(var) and not isarray(var)
  63. def ischaracterarray(var):
  64. return ischaracter_or_characterarray(var) and isarray(var)
  65. def isstring_or_stringarray(var):
  66. return _ischaracter(var) and 'charselector' in var
  67. def isstring(var):
  68. return isstring_or_stringarray(var) and not isarray(var)
  69. def isstringarray(var):
  70. return isstring_or_stringarray(var) and isarray(var)
  71. def isarrayofstrings(var): # obsolete?
  72. # leaving out '*' for now so that `character*(*) a(m)` and `character
  73. # a(m,*)` are treated differently. Luckily `character**` is illegal.
  74. return isstringarray(var) and var['dimension'][-1] == '(*)'
  75. def isarray(var):
  76. return 'dimension' in var and not isexternal(var)
  77. def isscalar(var):
  78. return not (isarray(var) or isstring(var) or isexternal(var))
  79. def iscomplex(var):
  80. return isscalar(var) and \
  81. var.get('typespec') in ['complex', 'double complex']
  82. def islogical(var):
  83. return isscalar(var) and var.get('typespec') == 'logical'
  84. def isinteger(var):
  85. return isscalar(var) and var.get('typespec') == 'integer'
  86. def isreal(var):
  87. return isscalar(var) and var.get('typespec') == 'real'
  88. def get_kind(var):
  89. try:
  90. return var['kindselector']['*']
  91. except KeyError:
  92. try:
  93. return var['kindselector']['kind']
  94. except KeyError:
  95. pass
  96. def isint1(var):
  97. return var.get('typespec') == 'integer' \
  98. and get_kind(var) == '1' and not isarray(var)
  99. def islong_long(var):
  100. if not isscalar(var):
  101. return 0
  102. if var.get('typespec') not in ['integer', 'logical']:
  103. return 0
  104. return get_kind(var) == '8'
  105. def isunsigned_char(var):
  106. if not isscalar(var):
  107. return 0
  108. if var.get('typespec') != 'integer':
  109. return 0
  110. return get_kind(var) == '-1'
  111. def isunsigned_short(var):
  112. if not isscalar(var):
  113. return 0
  114. if var.get('typespec') != 'integer':
  115. return 0
  116. return get_kind(var) == '-2'
  117. def isunsigned(var):
  118. if not isscalar(var):
  119. return 0
  120. if var.get('typespec') != 'integer':
  121. return 0
  122. return get_kind(var) == '-4'
  123. def isunsigned_long_long(var):
  124. if not isscalar(var):
  125. return 0
  126. if var.get('typespec') != 'integer':
  127. return 0
  128. return get_kind(var) == '-8'
  129. def isdouble(var):
  130. if not isscalar(var):
  131. return 0
  132. if not var.get('typespec') == 'real':
  133. return 0
  134. return get_kind(var) == '8'
  135. def islong_double(var):
  136. if not isscalar(var):
  137. return 0
  138. if not var.get('typespec') == 'real':
  139. return 0
  140. return get_kind(var) == '16'
  141. def islong_complex(var):
  142. if not iscomplex(var):
  143. return 0
  144. return get_kind(var) == '32'
  145. def iscomplexarray(var):
  146. return isarray(var) and \
  147. var.get('typespec') in ['complex', 'double complex']
  148. def isint1array(var):
  149. return isarray(var) and var.get('typespec') == 'integer' \
  150. and get_kind(var) == '1'
  151. def isunsigned_chararray(var):
  152. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  153. and get_kind(var) == '-1'
  154. def isunsigned_shortarray(var):
  155. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  156. and get_kind(var) == '-2'
  157. def isunsignedarray(var):
  158. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  159. and get_kind(var) == '-4'
  160. def isunsigned_long_longarray(var):
  161. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  162. and get_kind(var) == '-8'
  163. def issigned_chararray(var):
  164. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  165. and get_kind(var) == '1'
  166. def issigned_shortarray(var):
  167. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  168. and get_kind(var) == '2'
  169. def issigned_array(var):
  170. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  171. and get_kind(var) == '4'
  172. def issigned_long_longarray(var):
  173. return isarray(var) and var.get('typespec') in ['integer', 'logical']\
  174. and get_kind(var) == '8'
  175. def isallocatable(var):
  176. return 'attrspec' in var and 'allocatable' in var['attrspec']
  177. def ismutable(var):
  178. return not ('dimension' not in var or isstring(var))
  179. def ismoduleroutine(rout):
  180. return 'modulename' in rout
  181. def ismodule(rout):
  182. return 'block' in rout and 'module' == rout['block']
  183. def isfunction(rout):
  184. return 'block' in rout and 'function' == rout['block']
  185. def isfunction_wrap(rout):
  186. if isintent_c(rout):
  187. return 0
  188. return wrapfuncs and isfunction(rout) and (not isexternal(rout))
  189. def issubroutine(rout):
  190. return 'block' in rout and 'subroutine' == rout['block']
  191. def issubroutine_wrap(rout):
  192. if isintent_c(rout):
  193. return 0
  194. return issubroutine(rout) and hasassumedshape(rout)
  195. def isattr_value(var):
  196. return 'value' in var.get('attrspec', [])
  197. def hasassumedshape(rout):
  198. if rout.get('hasassumedshape'):
  199. return True
  200. for a in rout['args']:
  201. for d in rout['vars'].get(a, {}).get('dimension', []):
  202. if d == ':':
  203. rout['hasassumedshape'] = True
  204. return True
  205. return False
  206. def requiresf90wrapper(rout):
  207. return ismoduleroutine(rout) or hasassumedshape(rout)
  208. def isroutine(rout):
  209. return isfunction(rout) or issubroutine(rout)
  210. def islogicalfunction(rout):
  211. if not isfunction(rout):
  212. return 0
  213. if 'result' in rout:
  214. a = rout['result']
  215. else:
  216. a = rout['name']
  217. if a in rout['vars']:
  218. return islogical(rout['vars'][a])
  219. return 0
  220. def islong_longfunction(rout):
  221. if not isfunction(rout):
  222. return 0
  223. if 'result' in rout:
  224. a = rout['result']
  225. else:
  226. a = rout['name']
  227. if a in rout['vars']:
  228. return islong_long(rout['vars'][a])
  229. return 0
  230. def islong_doublefunction(rout):
  231. if not isfunction(rout):
  232. return 0
  233. if 'result' in rout:
  234. a = rout['result']
  235. else:
  236. a = rout['name']
  237. if a in rout['vars']:
  238. return islong_double(rout['vars'][a])
  239. return 0
  240. def iscomplexfunction(rout):
  241. if not isfunction(rout):
  242. return 0
  243. if 'result' in rout:
  244. a = rout['result']
  245. else:
  246. a = rout['name']
  247. if a in rout['vars']:
  248. return iscomplex(rout['vars'][a])
  249. return 0
  250. def iscomplexfunction_warn(rout):
  251. if iscomplexfunction(rout):
  252. outmess("""\
  253. **************************************************************
  254. Warning: code with a function returning complex value
  255. may not work correctly with your Fortran compiler.
  256. When using GNU gcc/g77 compilers, codes should work
  257. correctly for callbacks with:
  258. f2py -c -DF2PY_CB_RETURNCOMPLEX
  259. **************************************************************\n""")
  260. return 1
  261. return 0
  262. def isstringfunction(rout):
  263. if not isfunction(rout):
  264. return 0
  265. if 'result' in rout:
  266. a = rout['result']
  267. else:
  268. a = rout['name']
  269. if a in rout['vars']:
  270. return isstring(rout['vars'][a])
  271. return 0
  272. def hasexternals(rout):
  273. return 'externals' in rout and rout['externals']
  274. def isthreadsafe(rout):
  275. return 'f2pyenhancements' in rout and \
  276. 'threadsafe' in rout['f2pyenhancements']
  277. def hasvariables(rout):
  278. return 'vars' in rout and rout['vars']
  279. def isoptional(var):
  280. return ('attrspec' in var and 'optional' in var['attrspec'] and
  281. 'required' not in var['attrspec']) and isintent_nothide(var)
  282. def isexternal(var):
  283. return 'attrspec' in var and 'external' in var['attrspec']
  284. def getdimension(var):
  285. dimpattern = r"\((.*?)\)"
  286. if 'attrspec' in var.keys():
  287. if any('dimension' in s for s in var['attrspec']):
  288. return next(re.findall(dimpattern, v) for v in var['attrspec'])
  289. def isrequired(var):
  290. return not isoptional(var) and isintent_nothide(var)
  291. def iscstyledirective(f2py_line):
  292. directives = {"callstatement", "callprotoargument", "pymethoddef"}
  293. return any(directive in f2py_line.lower() for directive in directives)
  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 isvariable(var):
  354. # heuristic to find public/private declarations of filtered subroutines
  355. if len(var) == 1 and 'attrspec' in var and \
  356. var['attrspec'][0] in ('public', 'private'):
  357. is_var = False
  358. else:
  359. is_var = True
  360. return is_var
  361. def hasinitvalue(var):
  362. return '=' in var
  363. def hasinitvalueasstring(var):
  364. if not hasinitvalue(var):
  365. return 0
  366. return var['='][0] in ['"', "'"]
  367. def hasnote(var):
  368. return 'note' in var
  369. def hasresultnote(rout):
  370. if not isfunction(rout):
  371. return 0
  372. if 'result' in rout:
  373. a = rout['result']
  374. else:
  375. a = rout['name']
  376. if a in rout['vars']:
  377. return hasnote(rout['vars'][a])
  378. return 0
  379. def hascommon(rout):
  380. return 'common' in rout
  381. def containscommon(rout):
  382. if hascommon(rout):
  383. return 1
  384. if hasbody(rout):
  385. for b in rout['body']:
  386. if containscommon(b):
  387. return 1
  388. return 0
  389. def hasderivedtypes(rout):
  390. return ('block' in rout) and rout['block'] == 'type'
  391. def containsderivedtypes(rout):
  392. if hasderivedtypes(rout):
  393. return 1
  394. if hasbody(rout):
  395. for b in rout['body']:
  396. if hasderivedtypes(b):
  397. return 1
  398. return 0
  399. def containsmodule(block):
  400. if ismodule(block):
  401. return 1
  402. if not hasbody(block):
  403. return 0
  404. for b in block['body']:
  405. if containsmodule(b):
  406. return 1
  407. return 0
  408. def hasbody(rout):
  409. return 'body' in rout
  410. def hascallstatement(rout):
  411. return getcallstatement(rout) is not None
  412. def istrue(var):
  413. return 1
  414. def isfalse(var):
  415. return 0
  416. class F2PYError(Exception):
  417. pass
  418. class throw_error:
  419. def __init__(self, mess):
  420. self.mess = mess
  421. def __call__(self, var):
  422. mess = f'\n\n var = {var}\n Message: {self.mess}\n'
  423. raise F2PYError(mess)
  424. def l_and(*f):
  425. l1, l2 = 'lambda v', []
  426. for i in range(len(f)):
  427. l1 = '%s,f%d=f[%d]' % (l1, i, i)
  428. l2.append('f%d(v)' % (i))
  429. return eval(f"{l1}:{' and '.join(l2)}")
  430. def l_or(*f):
  431. l1, l2 = 'lambda v', []
  432. for i in range(len(f)):
  433. l1 = '%s,f%d=f[%d]' % (l1, i, i)
  434. l2.append('f%d(v)' % (i))
  435. return eval(f"{l1}:{' or '.join(l2)}")
  436. def l_not(f):
  437. return eval('lambda v,f=f:not f(v)')
  438. def isdummyroutine(rout):
  439. try:
  440. return rout['f2pyenhancements']['fortranname'] == ''
  441. except KeyError:
  442. return 0
  443. def getfortranname(rout):
  444. try:
  445. name = rout['f2pyenhancements']['fortranname']
  446. if name == '':
  447. raise KeyError
  448. if not name:
  449. errmess(f"Failed to use fortranname from {rout['f2pyenhancements']}\n")
  450. raise KeyError
  451. except KeyError:
  452. name = rout['name']
  453. return name
  454. def getmultilineblock(rout, blockname, comment=1, counter=0):
  455. try:
  456. r = rout['f2pyenhancements'].get(blockname)
  457. except KeyError:
  458. return
  459. if not r:
  460. return
  461. if counter > 0 and isinstance(r, str):
  462. return
  463. if isinstance(r, list):
  464. if counter >= len(r):
  465. return
  466. r = r[counter]
  467. if r[:3] == "'''":
  468. if comment:
  469. r = '\t/* start ' + blockname + \
  470. ' multiline (' + repr(counter) + ') */\n' + r[3:]
  471. else:
  472. r = r[3:]
  473. if r[-3:] == "'''":
  474. if comment:
  475. r = r[:-3] + '\n\t/* end multiline (' + repr(counter) + ')*/'
  476. else:
  477. r = r[:-3]
  478. else:
  479. errmess(f"{blockname} multiline block should end with `'''`: {repr(r)}\n")
  480. return r
  481. def getcallstatement(rout):
  482. return getmultilineblock(rout, 'callstatement')
  483. def getcallprotoargument(rout, cb_map={}):
  484. r = getmultilineblock(rout, 'callprotoargument', comment=0)
  485. if r:
  486. return r
  487. if hascallstatement(rout):
  488. outmess(
  489. 'warning: callstatement is defined without callprotoargument\n')
  490. return
  491. from .capi_maps import getctype
  492. arg_types, arg_types2 = [], []
  493. if l_and(isstringfunction, l_not(isfunction_wrap))(rout):
  494. arg_types.extend(['char*', 'size_t'])
  495. for n in rout['args']:
  496. var = rout['vars'][n]
  497. if isintent_callback(var):
  498. continue
  499. if n in cb_map:
  500. ctype = cb_map[n] + '_typedef'
  501. else:
  502. ctype = getctype(var)
  503. if l_and(isintent_c, l_or(isscalar, iscomplex))(var):
  504. pass
  505. elif isstring(var):
  506. pass
  507. elif not isattr_value(var):
  508. ctype = ctype + '*'
  509. if (isstring(var)
  510. or isarrayofstrings(var) # obsolete?
  511. or isstringarray(var)):
  512. arg_types2.append('size_t')
  513. arg_types.append(ctype)
  514. proto_args = ','.join(arg_types + arg_types2)
  515. if not proto_args:
  516. proto_args = 'void'
  517. return proto_args
  518. def getusercode(rout):
  519. return getmultilineblock(rout, 'usercode')
  520. def getusercode1(rout):
  521. return getmultilineblock(rout, 'usercode', counter=1)
  522. def getpymethoddef(rout):
  523. return getmultilineblock(rout, 'pymethoddef')
  524. def getargs(rout):
  525. sortargs, args = [], []
  526. if 'args' in rout:
  527. args = rout['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 = rout['args']
  537. return args, sortargs
  538. def getargs2(rout):
  539. sortargs, args = [], rout.get('args', [])
  540. auxvars = [a for a in rout['vars'].keys() if isintent_aux(rout['vars'][a])
  541. and a not in args]
  542. args = auxvars + args
  543. if 'sortvars' in rout:
  544. for a in rout['sortvars']:
  545. if a in args:
  546. sortargs.append(a)
  547. for a in args:
  548. if a not in sortargs:
  549. sortargs.append(a)
  550. else:
  551. sortargs = auxvars + rout['args']
  552. return args, sortargs
  553. def getrestdoc(rout):
  554. if 'f2pymultilines' not in rout:
  555. return None
  556. k = None
  557. if rout['block'] == 'python module':
  558. k = rout['block'], rout['name']
  559. return rout['f2pymultilines'].get(k, None)
  560. def gentitle(name):
  561. ln = (80 - len(name) - 6) // 2
  562. return f"/*{ln * '*'} {name} {ln * '*'}*/"
  563. def flatlist(lst):
  564. if isinstance(lst, list):
  565. return reduce(lambda x, y, f=flatlist: x + f(y), lst, [])
  566. return [lst]
  567. def stripcomma(s):
  568. if s and s[-1] == ',':
  569. return s[:-1]
  570. return s
  571. def replace(str, d, defaultsep=''):
  572. if isinstance(d, list):
  573. return [replace(str, _m, defaultsep) for _m in d]
  574. if isinstance(str, list):
  575. return [replace(_m, d, defaultsep) for _m in str]
  576. for k in 2 * list(d.keys()):
  577. if k == 'separatorsfor':
  578. continue
  579. if 'separatorsfor' in d and k in d['separatorsfor']:
  580. sep = d['separatorsfor'][k]
  581. else:
  582. sep = defaultsep
  583. if isinstance(d[k], list):
  584. str = str.replace(f'#{k}#', sep.join(flatlist(d[k])))
  585. else:
  586. str = str.replace(f'#{k}#', d[k])
  587. return str
  588. def dictappend(rd, ar):
  589. if isinstance(ar, list):
  590. for a in ar:
  591. rd = dictappend(rd, a)
  592. return rd
  593. for k in ar.keys():
  594. if k[0] == '_':
  595. continue
  596. if k in rd:
  597. if isinstance(rd[k], str):
  598. rd[k] = [rd[k]]
  599. if isinstance(rd[k], list):
  600. if isinstance(ar[k], list):
  601. rd[k] = rd[k] + ar[k]
  602. else:
  603. rd[k].append(ar[k])
  604. elif isinstance(rd[k], dict):
  605. if isinstance(ar[k], dict):
  606. if k == 'separatorsfor':
  607. for k1 in ar[k].keys():
  608. if k1 not in rd[k]:
  609. rd[k][k1] = ar[k][k1]
  610. else:
  611. rd[k] = dictappend(rd[k], ar[k])
  612. else:
  613. rd[k] = ar[k]
  614. return rd
  615. def applyrules(rules, d, var={}):
  616. ret = {}
  617. if isinstance(rules, list):
  618. for r in rules:
  619. rr = applyrules(r, d, var)
  620. ret = dictappend(ret, rr)
  621. if '_break' in rr:
  622. break
  623. return ret
  624. if '_check' in rules and (not rules['_check'](var)):
  625. return ret
  626. if 'need' in rules:
  627. res = applyrules({'needs': rules['need']}, d, var)
  628. if 'needs' in res:
  629. cfuncs.append_needs(res['needs'])
  630. for k in rules.keys():
  631. if k == 'separatorsfor':
  632. ret[k] = rules[k]
  633. continue
  634. if isinstance(rules[k], str):
  635. ret[k] = replace(rules[k], d)
  636. elif isinstance(rules[k], list):
  637. ret[k] = []
  638. for i in rules[k]:
  639. ar = applyrules({k: i}, d, var)
  640. if k in ar:
  641. ret[k].append(ar[k])
  642. elif k[0] == '_':
  643. continue
  644. elif isinstance(rules[k], dict):
  645. ret[k] = []
  646. for k1 in rules[k].keys():
  647. if isinstance(k1, types.FunctionType) and k1(var):
  648. if isinstance(rules[k][k1], list):
  649. for i in rules[k][k1]:
  650. if isinstance(i, dict):
  651. res = applyrules({'supertext': i}, d, var)
  652. i = res.get('supertext', '')
  653. ret[k].append(replace(i, d))
  654. else:
  655. i = rules[k][k1]
  656. if isinstance(i, dict):
  657. res = applyrules({'supertext': i}, d)
  658. i = res.get('supertext', '')
  659. ret[k].append(replace(i, d))
  660. else:
  661. errmess(f'applyrules: ignoring rule {repr(rules[k])}.\n')
  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(f'\tMapping "{k}(kind={k1})" to "{v1}\"\n')
  740. f2cmap_mapped.append(v1)
  741. elif verbose:
  742. errmess(
  743. "\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"
  744. % (k, k1, v1, v1, list(c2py_map.keys()))
  745. )
  746. return f2cmap_all, f2cmap_mapped