auxfuncs.py 21 KB

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