auxfuncs.py 24 KB

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