capi_maps.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. #!/usr/bin/env python3
  2. """
  3. Copyright 1999,2000 Pearu Peterson all rights reserved,
  4. Pearu Peterson <pearu@ioc.ee>
  5. Permission to use, modify, and distribute this software is given under the
  6. terms of the NumPy License.
  7. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  8. $Date: 2005/05/06 10:57:33 $
  9. Pearu Peterson
  10. """
  11. from . import __version__
  12. f2py_version = __version__.version
  13. import copy
  14. import re
  15. import os
  16. from .crackfortran import markoutercomma
  17. from . import cb_rules
  18. # The environment provided by auxfuncs.py is needed for some calls to eval.
  19. # As the needed functions cannot be determined by static inspection of the
  20. # code, it is safest to use import * pending a major refactoring of f2py.
  21. from .auxfuncs import *
  22. __all__ = [
  23. 'getctype', 'getstrlength', 'getarrdims', 'getpydocsign',
  24. 'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map',
  25. 'cb_sign2map', 'cb_routsign2map', 'common_sign2map'
  26. ]
  27. # Numarray and Numeric users should set this False
  28. using_newcore = True
  29. depargs = []
  30. lcb_map = {}
  31. lcb2_map = {}
  32. # forced casting: mainly caused by the fact that Python or Numeric
  33. # C/APIs do not support the corresponding C types.
  34. c2py_map = {'double': 'float',
  35. 'float': 'float', # forced casting
  36. 'long_double': 'float', # forced casting
  37. 'char': 'int', # forced casting
  38. 'signed_char': 'int', # forced casting
  39. 'unsigned_char': 'int', # forced casting
  40. 'short': 'int', # forced casting
  41. 'unsigned_short': 'int', # forced casting
  42. 'int': 'int', # (forced casting)
  43. 'long': 'int',
  44. 'long_long': 'long',
  45. 'unsigned': 'int', # forced casting
  46. 'complex_float': 'complex', # forced casting
  47. 'complex_double': 'complex',
  48. 'complex_long_double': 'complex', # forced casting
  49. 'string': 'string',
  50. }
  51. c2capi_map = {'double': 'NPY_DOUBLE',
  52. 'float': 'NPY_FLOAT',
  53. 'long_double': 'NPY_DOUBLE', # forced casting
  54. 'char': 'NPY_STRING',
  55. 'unsigned_char': 'NPY_UBYTE',
  56. 'signed_char': 'NPY_BYTE',
  57. 'short': 'NPY_SHORT',
  58. 'unsigned_short': 'NPY_USHORT',
  59. 'int': 'NPY_INT',
  60. 'unsigned': 'NPY_UINT',
  61. 'long': 'NPY_LONG',
  62. 'long_long': 'NPY_LONG', # forced casting
  63. 'complex_float': 'NPY_CFLOAT',
  64. 'complex_double': 'NPY_CDOUBLE',
  65. 'complex_long_double': 'NPY_CDOUBLE', # forced casting
  66. 'string': 'NPY_STRING'}
  67. # These new maps aren't used anywhere yet, but should be by default
  68. # unless building numeric or numarray extensions.
  69. if using_newcore:
  70. c2capi_map = {'double': 'NPY_DOUBLE',
  71. 'float': 'NPY_FLOAT',
  72. 'long_double': 'NPY_LONGDOUBLE',
  73. 'char': 'NPY_BYTE',
  74. 'unsigned_char': 'NPY_UBYTE',
  75. 'signed_char': 'NPY_BYTE',
  76. 'short': 'NPY_SHORT',
  77. 'unsigned_short': 'NPY_USHORT',
  78. 'int': 'NPY_INT',
  79. 'unsigned': 'NPY_UINT',
  80. 'long': 'NPY_LONG',
  81. 'unsigned_long': 'NPY_ULONG',
  82. 'long_long': 'NPY_LONGLONG',
  83. 'unsigned_long_long': 'NPY_ULONGLONG',
  84. 'complex_float': 'NPY_CFLOAT',
  85. 'complex_double': 'NPY_CDOUBLE',
  86. 'complex_long_double': 'NPY_CDOUBLE',
  87. 'string':'NPY_STRING'
  88. }
  89. c2pycode_map = {'double': 'd',
  90. 'float': 'f',
  91. 'long_double': 'd', # forced casting
  92. 'char': '1',
  93. 'signed_char': '1',
  94. 'unsigned_char': 'b',
  95. 'short': 's',
  96. 'unsigned_short': 'w',
  97. 'int': 'i',
  98. 'unsigned': 'u',
  99. 'long': 'l',
  100. 'long_long': 'L',
  101. 'complex_float': 'F',
  102. 'complex_double': 'D',
  103. 'complex_long_double': 'D', # forced casting
  104. 'string': 'c'
  105. }
  106. if using_newcore:
  107. c2pycode_map = {'double': 'd',
  108. 'float': 'f',
  109. 'long_double': 'g',
  110. 'char': 'b',
  111. 'unsigned_char': 'B',
  112. 'signed_char': 'b',
  113. 'short': 'h',
  114. 'unsigned_short': 'H',
  115. 'int': 'i',
  116. 'unsigned': 'I',
  117. 'long': 'l',
  118. 'unsigned_long': 'L',
  119. 'long_long': 'q',
  120. 'unsigned_long_long': 'Q',
  121. 'complex_float': 'F',
  122. 'complex_double': 'D',
  123. 'complex_long_double': 'G',
  124. 'string': 'S'}
  125. c2buildvalue_map = {'double': 'd',
  126. 'float': 'f',
  127. 'char': 'b',
  128. 'signed_char': 'b',
  129. 'short': 'h',
  130. 'int': 'i',
  131. 'long': 'l',
  132. 'long_long': 'L',
  133. 'complex_float': 'N',
  134. 'complex_double': 'N',
  135. 'complex_long_double': 'N',
  136. 'string': 'y'}
  137. if using_newcore:
  138. # c2buildvalue_map=???
  139. pass
  140. f2cmap_all = {'real': {'': 'float', '4': 'float', '8': 'double',
  141. '12': 'long_double', '16': 'long_double'},
  142. 'integer': {'': 'int', '1': 'signed_char', '2': 'short',
  143. '4': 'int', '8': 'long_long',
  144. '-1': 'unsigned_char', '-2': 'unsigned_short',
  145. '-4': 'unsigned', '-8': 'unsigned_long_long'},
  146. 'complex': {'': 'complex_float', '8': 'complex_float',
  147. '16': 'complex_double', '24': 'complex_long_double',
  148. '32': 'complex_long_double'},
  149. 'complexkind': {'': 'complex_float', '4': 'complex_float',
  150. '8': 'complex_double', '12': 'complex_long_double',
  151. '16': 'complex_long_double'},
  152. 'logical': {'': 'int', '1': 'char', '2': 'short', '4': 'int',
  153. '8': 'long_long'},
  154. 'double complex': {'': 'complex_double'},
  155. 'double precision': {'': 'double'},
  156. 'byte': {'': 'char'},
  157. 'character': {'': 'string'}
  158. }
  159. f2cmap_default = copy.deepcopy(f2cmap_all)
  160. def load_f2cmap_file(f2cmap_file):
  161. global f2cmap_all
  162. f2cmap_all = copy.deepcopy(f2cmap_default)
  163. if f2cmap_file is None:
  164. # Default value
  165. f2cmap_file = '.f2py_f2cmap'
  166. if not os.path.isfile(f2cmap_file):
  167. return
  168. # User defined additions to f2cmap_all.
  169. # f2cmap_file must contain a dictionary of dictionaries, only. For
  170. # example, {'real':{'low':'float'}} means that Fortran 'real(low)' is
  171. # interpreted as C 'float'. This feature is useful for F90/95 users if
  172. # they use PARAMETERSs in type specifications.
  173. try:
  174. outmess('Reading f2cmap from {!r} ...\n'.format(f2cmap_file))
  175. with open(f2cmap_file, 'r') as f:
  176. d = eval(f.read(), {}, {})
  177. for k, d1 in list(d.items()):
  178. for k1 in list(d1.keys()):
  179. d1[k1.lower()] = d1[k1]
  180. d[k.lower()] = d[k]
  181. for k in list(d.keys()):
  182. if k not in f2cmap_all:
  183. f2cmap_all[k] = {}
  184. for k1 in list(d[k].keys()):
  185. if d[k][k1] in c2py_map:
  186. if k1 in f2cmap_all[k]:
  187. outmess(
  188. "\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n" % (k, k1, f2cmap_all[k][k1], d[k][k1]))
  189. f2cmap_all[k][k1] = d[k][k1]
  190. outmess('\tMapping "%s(kind=%s)" to "%s"\n' %
  191. (k, k1, d[k][k1]))
  192. else:
  193. errmess("\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n" % (
  194. k, k1, d[k][k1], d[k][k1], list(c2py_map.keys())))
  195. outmess('Successfully applied user defined f2cmap changes\n')
  196. except Exception as msg:
  197. errmess(
  198. 'Failed to apply user defined f2cmap changes: %s. Skipping.\n' % (msg))
  199. cformat_map = {'double': '%g',
  200. 'float': '%g',
  201. 'long_double': '%Lg',
  202. 'char': '%d',
  203. 'signed_char': '%d',
  204. 'unsigned_char': '%hhu',
  205. 'short': '%hd',
  206. 'unsigned_short': '%hu',
  207. 'int': '%d',
  208. 'unsigned': '%u',
  209. 'long': '%ld',
  210. 'unsigned_long': '%lu',
  211. 'long_long': '%ld',
  212. 'complex_float': '(%g,%g)',
  213. 'complex_double': '(%g,%g)',
  214. 'complex_long_double': '(%Lg,%Lg)',
  215. 'string': '%s',
  216. }
  217. # Auxiliary functions
  218. def getctype(var):
  219. """
  220. Determines C type
  221. """
  222. ctype = 'void'
  223. if isfunction(var):
  224. if 'result' in var:
  225. a = var['result']
  226. else:
  227. a = var['name']
  228. if a in var['vars']:
  229. return getctype(var['vars'][a])
  230. else:
  231. errmess('getctype: function %s has no return value?!\n' % a)
  232. elif issubroutine(var):
  233. return ctype
  234. elif 'typespec' in var and var['typespec'].lower() in f2cmap_all:
  235. typespec = var['typespec'].lower()
  236. f2cmap = f2cmap_all[typespec]
  237. ctype = f2cmap[''] # default type
  238. if 'kindselector' in var:
  239. if '*' in var['kindselector']:
  240. try:
  241. ctype = f2cmap[var['kindselector']['*']]
  242. except KeyError:
  243. errmess('getctype: "%s %s %s" not supported.\n' %
  244. (var['typespec'], '*', var['kindselector']['*']))
  245. elif 'kind' in var['kindselector']:
  246. if typespec + 'kind' in f2cmap_all:
  247. f2cmap = f2cmap_all[typespec + 'kind']
  248. try:
  249. ctype = f2cmap[var['kindselector']['kind']]
  250. except KeyError:
  251. if typespec in f2cmap_all:
  252. f2cmap = f2cmap_all[typespec]
  253. try:
  254. ctype = f2cmap[str(var['kindselector']['kind'])]
  255. except KeyError:
  256. errmess('getctype: "%s(kind=%s)" is mapped to C "%s" (to override define dict(%s = dict(%s="<C typespec>")) in %s/.f2py_f2cmap file).\n'
  257. % (typespec, var['kindselector']['kind'], ctype,
  258. typespec, var['kindselector']['kind'], os.getcwd()))
  259. else:
  260. if not isexternal(var):
  261. errmess(
  262. 'getctype: No C-type found in "%s", assuming void.\n' % var)
  263. return ctype
  264. def getstrlength(var):
  265. if isstringfunction(var):
  266. if 'result' in var:
  267. a = var['result']
  268. else:
  269. a = var['name']
  270. if a in var['vars']:
  271. return getstrlength(var['vars'][a])
  272. else:
  273. errmess('getstrlength: function %s has no return value?!\n' % a)
  274. if not isstring(var):
  275. errmess(
  276. 'getstrlength: expected a signature of a string but got: %s\n' % (repr(var)))
  277. len = '1'
  278. if 'charselector' in var:
  279. a = var['charselector']
  280. if '*' in a:
  281. len = a['*']
  282. elif 'len' in a:
  283. len = a['len']
  284. if re.match(r'\(\s*(\*|:)\s*\)', len) or re.match(r'(\*|:)', len):
  285. if isintent_hide(var):
  286. errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n' % (
  287. repr(var)))
  288. len = '-1'
  289. return len
  290. def getarrdims(a, var, verbose=0):
  291. ret = {}
  292. if isstring(var) and not isarray(var):
  293. ret['dims'] = getstrlength(var)
  294. ret['size'] = ret['dims']
  295. ret['rank'] = '1'
  296. elif isscalar(var):
  297. ret['size'] = '1'
  298. ret['rank'] = '0'
  299. ret['dims'] = ''
  300. elif isarray(var):
  301. dim = copy.copy(var['dimension'])
  302. ret['size'] = '*'.join(dim)
  303. try:
  304. ret['size'] = repr(eval(ret['size']))
  305. except Exception:
  306. pass
  307. ret['dims'] = ','.join(dim)
  308. ret['rank'] = repr(len(dim))
  309. ret['rank*[-1]'] = repr(len(dim) * [-1])[1:-1]
  310. for i in range(len(dim)): # solve dim for dependencies
  311. v = []
  312. if dim[i] in depargs:
  313. v = [dim[i]]
  314. else:
  315. for va in depargs:
  316. if re.match(r'.*?\b%s\b.*' % va, dim[i]):
  317. v.append(va)
  318. for va in v:
  319. if depargs.index(va) > depargs.index(a):
  320. dim[i] = '*'
  321. break
  322. ret['setdims'], i = '', -1
  323. for d in dim:
  324. i = i + 1
  325. if d not in ['*', ':', '(*)', '(:)']:
  326. ret['setdims'] = '%s#varname#_Dims[%d]=%s,' % (
  327. ret['setdims'], i, d)
  328. if ret['setdims']:
  329. ret['setdims'] = ret['setdims'][:-1]
  330. ret['cbsetdims'], i = '', -1
  331. for d in var['dimension']:
  332. i = i + 1
  333. if d not in ['*', ':', '(*)', '(:)']:
  334. ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
  335. ret['cbsetdims'], i, d)
  336. elif isintent_in(var):
  337. outmess('getarrdims:warning: assumed shape array, using 0 instead of %r\n'
  338. % (d))
  339. ret['cbsetdims'] = '%s#varname#_Dims[%d]=%s,' % (
  340. ret['cbsetdims'], i, 0)
  341. elif verbose:
  342. errmess(
  343. 'getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n' % (repr(a), repr(d)))
  344. if ret['cbsetdims']:
  345. ret['cbsetdims'] = ret['cbsetdims'][:-1]
  346. # if not isintent_c(var):
  347. # var['dimension'].reverse()
  348. return ret
  349. def getpydocsign(a, var):
  350. global lcb_map
  351. if isfunction(var):
  352. if 'result' in var:
  353. af = var['result']
  354. else:
  355. af = var['name']
  356. if af in var['vars']:
  357. return getpydocsign(af, var['vars'][af])
  358. else:
  359. errmess('getctype: function %s has no return value?!\n' % af)
  360. return '', ''
  361. sig, sigout = a, a
  362. opt = ''
  363. if isintent_in(var):
  364. opt = 'input'
  365. elif isintent_inout(var):
  366. opt = 'in/output'
  367. out_a = a
  368. if isintent_out(var):
  369. for k in var['intent']:
  370. if k[:4] == 'out=':
  371. out_a = k[4:]
  372. break
  373. init = ''
  374. ctype = getctype(var)
  375. if hasinitvalue(var):
  376. init, showinit = getinit(a, var)
  377. init = ', optional\\n Default: %s' % showinit
  378. if isscalar(var):
  379. if isintent_inout(var):
  380. sig = '%s : %s rank-0 array(%s,\'%s\')%s' % (a, opt, c2py_map[ctype],
  381. c2pycode_map[ctype], init)
  382. else:
  383. sig = '%s : %s %s%s' % (a, opt, c2py_map[ctype], init)
  384. sigout = '%s : %s' % (out_a, c2py_map[ctype])
  385. elif isstring(var):
  386. if isintent_inout(var):
  387. sig = '%s : %s rank-0 array(string(len=%s),\'c\')%s' % (
  388. a, opt, getstrlength(var), init)
  389. else:
  390. sig = '%s : %s string(len=%s)%s' % (
  391. a, opt, getstrlength(var), init)
  392. sigout = '%s : string(len=%s)' % (out_a, getstrlength(var))
  393. elif isarray(var):
  394. dim = var['dimension']
  395. rank = repr(len(dim))
  396. sig = '%s : %s rank-%s array(\'%s\') with bounds (%s)%s' % (a, opt, rank,
  397. c2pycode_map[
  398. ctype],
  399. ','.join(dim), init)
  400. if a == out_a:
  401. sigout = '%s : rank-%s array(\'%s\') with bounds (%s)'\
  402. % (a, rank, c2pycode_map[ctype], ','.join(dim))
  403. else:
  404. sigout = '%s : rank-%s array(\'%s\') with bounds (%s) and %s storage'\
  405. % (out_a, rank, c2pycode_map[ctype], ','.join(dim), a)
  406. elif isexternal(var):
  407. ua = ''
  408. if a in lcb_map and lcb_map[a] in lcb2_map and 'argname' in lcb2_map[lcb_map[a]]:
  409. ua = lcb2_map[lcb_map[a]]['argname']
  410. if not ua == a:
  411. ua = ' => %s' % ua
  412. else:
  413. ua = ''
  414. sig = '%s : call-back function%s' % (a, ua)
  415. sigout = sig
  416. else:
  417. errmess(
  418. 'getpydocsign: Could not resolve docsignature for "%s".\\n' % a)
  419. return sig, sigout
  420. def getarrdocsign(a, var):
  421. ctype = getctype(var)
  422. if isstring(var) and (not isarray(var)):
  423. sig = '%s : rank-0 array(string(len=%s),\'c\')' % (a,
  424. getstrlength(var))
  425. elif isscalar(var):
  426. sig = '%s : rank-0 array(%s,\'%s\')' % (a, c2py_map[ctype],
  427. c2pycode_map[ctype],)
  428. elif isarray(var):
  429. dim = var['dimension']
  430. rank = repr(len(dim))
  431. sig = '%s : rank-%s array(\'%s\') with bounds (%s)' % (a, rank,
  432. c2pycode_map[
  433. ctype],
  434. ','.join(dim))
  435. return sig
  436. def getinit(a, var):
  437. if isstring(var):
  438. init, showinit = '""', "''"
  439. else:
  440. init, showinit = '', ''
  441. if hasinitvalue(var):
  442. init = var['=']
  443. showinit = init
  444. if iscomplex(var) or iscomplexarray(var):
  445. ret = {}
  446. try:
  447. v = var["="]
  448. if ',' in v:
  449. ret['init.r'], ret['init.i'] = markoutercomma(
  450. v[1:-1]).split('@,@')
  451. else:
  452. v = eval(v, {}, {})
  453. ret['init.r'], ret['init.i'] = str(v.real), str(v.imag)
  454. except Exception:
  455. raise ValueError(
  456. 'getinit: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a))
  457. if isarray(var):
  458. init = '(capi_c.r=%s,capi_c.i=%s,capi_c)' % (
  459. ret['init.r'], ret['init.i'])
  460. elif isstring(var):
  461. if not init:
  462. init, showinit = '""', "''"
  463. if init[0] == "'":
  464. init = '"%s"' % (init[1:-1].replace('"', '\\"'))
  465. if init[0] == '"':
  466. showinit = "'%s'" % (init[1:-1])
  467. return init, showinit
  468. def sign2map(a, var):
  469. """
  470. varname,ctype,atype
  471. init,init.r,init.i,pytype
  472. vardebuginfo,vardebugshowvalue,varshowvalue
  473. varrfromat
  474. intent
  475. """
  476. out_a = a
  477. if isintent_out(var):
  478. for k in var['intent']:
  479. if k[:4] == 'out=':
  480. out_a = k[4:]
  481. break
  482. ret = {'varname': a, 'outvarname': out_a, 'ctype': getctype(var)}
  483. intent_flags = []
  484. for f, s in isintent_dict.items():
  485. if f(var):
  486. intent_flags.append('F2PY_%s' % s)
  487. if intent_flags:
  488. # XXX: Evaluate intent_flags here.
  489. ret['intent'] = '|'.join(intent_flags)
  490. else:
  491. ret['intent'] = 'F2PY_INTENT_IN'
  492. if isarray(var):
  493. ret['varrformat'] = 'N'
  494. elif ret['ctype'] in c2buildvalue_map:
  495. ret['varrformat'] = c2buildvalue_map[ret['ctype']]
  496. else:
  497. ret['varrformat'] = 'O'
  498. ret['init'], ret['showinit'] = getinit(a, var)
  499. if hasinitvalue(var) and iscomplex(var) and not isarray(var):
  500. ret['init.r'], ret['init.i'] = markoutercomma(
  501. ret['init'][1:-1]).split('@,@')
  502. if isexternal(var):
  503. ret['cbnamekey'] = a
  504. if a in lcb_map:
  505. ret['cbname'] = lcb_map[a]
  506. ret['maxnofargs'] = lcb2_map[lcb_map[a]]['maxnofargs']
  507. ret['nofoptargs'] = lcb2_map[lcb_map[a]]['nofoptargs']
  508. ret['cbdocstr'] = lcb2_map[lcb_map[a]]['docstr']
  509. ret['cblatexdocstr'] = lcb2_map[lcb_map[a]]['latexdocstr']
  510. else:
  511. ret['cbname'] = a
  512. errmess('sign2map: Confused: external %s is not in lcb_map%s.\n' % (
  513. a, list(lcb_map.keys())))
  514. if isstring(var):
  515. ret['length'] = getstrlength(var)
  516. if isarray(var):
  517. ret = dictappend(ret, getarrdims(a, var))
  518. dim = copy.copy(var['dimension'])
  519. if ret['ctype'] in c2capi_map:
  520. ret['atype'] = c2capi_map[ret['ctype']]
  521. # Debug info
  522. if debugcapi(var):
  523. il = [isintent_in, 'input', isintent_out, 'output',
  524. isintent_inout, 'inoutput', isrequired, 'required',
  525. isoptional, 'optional', isintent_hide, 'hidden',
  526. iscomplex, 'complex scalar',
  527. l_and(isscalar, l_not(iscomplex)), 'scalar',
  528. isstring, 'string', isarray, 'array',
  529. iscomplexarray, 'complex array', isstringarray, 'string array',
  530. iscomplexfunction, 'complex function',
  531. l_and(isfunction, l_not(iscomplexfunction)), 'function',
  532. isexternal, 'callback',
  533. isintent_callback, 'callback',
  534. isintent_aux, 'auxiliary',
  535. ]
  536. rl = []
  537. for i in range(0, len(il), 2):
  538. if il[i](var):
  539. rl.append(il[i + 1])
  540. if isstring(var):
  541. rl.append('slen(%s)=%s' % (a, ret['length']))
  542. if isarray(var):
  543. ddim = ','.join(
  544. map(lambda x, y: '%s|%s' % (x, y), var['dimension'], dim))
  545. rl.append('dims(%s)' % ddim)
  546. if isexternal(var):
  547. ret['vardebuginfo'] = 'debug-capi:%s=>%s:%s' % (
  548. a, ret['cbname'], ','.join(rl))
  549. else:
  550. ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % (
  551. ret['ctype'], a, ret['showinit'], ','.join(rl))
  552. if isscalar(var):
  553. if ret['ctype'] in cformat_map:
  554. ret['vardebugshowvalue'] = 'debug-capi:%s=%s' % (
  555. a, cformat_map[ret['ctype']])
  556. if isstring(var):
  557. ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
  558. a, a)
  559. if isexternal(var):
  560. ret['vardebugshowvalue'] = 'debug-capi:%s=%%p' % (a)
  561. if ret['ctype'] in cformat_map:
  562. ret['varshowvalue'] = '#name#:%s=%s' % (a, cformat_map[ret['ctype']])
  563. ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
  564. if isstring(var):
  565. ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a)
  566. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
  567. if hasnote(var):
  568. ret['note'] = var['note']
  569. return ret
  570. def routsign2map(rout):
  571. """
  572. name,NAME,begintitle,endtitle
  573. rname,ctype,rformat
  574. routdebugshowvalue
  575. """
  576. global lcb_map
  577. name = rout['name']
  578. fname = getfortranname(rout)
  579. ret = {'name': name,
  580. 'texname': name.replace('_', '\\_'),
  581. 'name_lower': name.lower(),
  582. 'NAME': name.upper(),
  583. 'begintitle': gentitle(name),
  584. 'endtitle': gentitle('end of %s' % name),
  585. 'fortranname': fname,
  586. 'FORTRANNAME': fname.upper(),
  587. 'callstatement': getcallstatement(rout) or '',
  588. 'usercode': getusercode(rout) or '',
  589. 'usercode1': getusercode1(rout) or '',
  590. }
  591. if '_' in fname:
  592. ret['F_FUNC'] = 'F_FUNC_US'
  593. else:
  594. ret['F_FUNC'] = 'F_FUNC'
  595. if '_' in name:
  596. ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC_US'
  597. else:
  598. ret['F_WRAPPEDFUNC'] = 'F_WRAPPEDFUNC'
  599. lcb_map = {}
  600. if 'use' in rout:
  601. for u in rout['use'].keys():
  602. if u in cb_rules.cb_map:
  603. for un in cb_rules.cb_map[u]:
  604. ln = un[0]
  605. if 'map' in rout['use'][u]:
  606. for k in rout['use'][u]['map'].keys():
  607. if rout['use'][u]['map'][k] == un[0]:
  608. ln = k
  609. break
  610. lcb_map[ln] = un[1]
  611. elif 'externals' in rout and rout['externals']:
  612. errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n' % (
  613. ret['name'], repr(rout['externals'])))
  614. ret['callprotoargument'] = getcallprotoargument(rout, lcb_map) or ''
  615. if isfunction(rout):
  616. if 'result' in rout:
  617. a = rout['result']
  618. else:
  619. a = rout['name']
  620. ret['rname'] = a
  621. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
  622. ret['ctype'] = getctype(rout['vars'][a])
  623. if hasresultnote(rout):
  624. ret['resultnote'] = rout['vars'][a]['note']
  625. rout['vars'][a]['note'] = ['See elsewhere.']
  626. if ret['ctype'] in c2buildvalue_map:
  627. ret['rformat'] = c2buildvalue_map[ret['ctype']]
  628. else:
  629. ret['rformat'] = 'O'
  630. errmess('routsign2map: no c2buildvalue key for type %s\n' %
  631. (repr(ret['ctype'])))
  632. if debugcapi(rout):
  633. if ret['ctype'] in cformat_map:
  634. ret['routdebugshowvalue'] = 'debug-capi:%s=%s' % (
  635. a, cformat_map[ret['ctype']])
  636. if isstringfunction(rout):
  637. ret['routdebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
  638. a, a)
  639. if isstringfunction(rout):
  640. ret['rlength'] = getstrlength(rout['vars'][a])
  641. if ret['rlength'] == '-1':
  642. errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n' % (
  643. repr(rout['name'])))
  644. ret['rlength'] = '10'
  645. if hasnote(rout):
  646. ret['note'] = rout['note']
  647. rout['note'] = ['See elsewhere.']
  648. return ret
  649. def modsign2map(m):
  650. """
  651. modulename
  652. """
  653. if ismodule(m):
  654. ret = {'f90modulename': m['name'],
  655. 'F90MODULENAME': m['name'].upper(),
  656. 'texf90modulename': m['name'].replace('_', '\\_')}
  657. else:
  658. ret = {'modulename': m['name'],
  659. 'MODULENAME': m['name'].upper(),
  660. 'texmodulename': m['name'].replace('_', '\\_')}
  661. ret['restdoc'] = getrestdoc(m) or []
  662. if hasnote(m):
  663. ret['note'] = m['note']
  664. ret['usercode'] = getusercode(m) or ''
  665. ret['usercode1'] = getusercode1(m) or ''
  666. if m['body']:
  667. ret['interface_usercode'] = getusercode(m['body'][0]) or ''
  668. else:
  669. ret['interface_usercode'] = ''
  670. ret['pymethoddef'] = getpymethoddef(m) or ''
  671. if 'coutput' in m:
  672. ret['coutput'] = m['coutput']
  673. if 'f2py_wrapper_output' in m:
  674. ret['f2py_wrapper_output'] = m['f2py_wrapper_output']
  675. return ret
  676. def cb_sign2map(a, var, index=None):
  677. ret = {'varname': a}
  678. ret['varname_i'] = ret['varname']
  679. ret['ctype'] = getctype(var)
  680. if ret['ctype'] in c2capi_map:
  681. ret['atype'] = c2capi_map[ret['ctype']]
  682. if ret['ctype'] in cformat_map:
  683. ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
  684. if isarray(var):
  685. ret = dictappend(ret, getarrdims(a, var))
  686. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
  687. if hasnote(var):
  688. ret['note'] = var['note']
  689. var['note'] = ['See elsewhere.']
  690. return ret
  691. def cb_routsign2map(rout, um):
  692. """
  693. name,begintitle,endtitle,argname
  694. ctype,rctype,maxnofargs,nofoptargs,returncptr
  695. """
  696. ret = {'name': 'cb_%s_in_%s' % (rout['name'], um),
  697. 'returncptr': ''}
  698. if isintent_callback(rout):
  699. if '_' in rout['name']:
  700. F_FUNC = 'F_FUNC_US'
  701. else:
  702. F_FUNC = 'F_FUNC'
  703. ret['callbackname'] = '%s(%s,%s)' \
  704. % (F_FUNC,
  705. rout['name'].lower(),
  706. rout['name'].upper(),
  707. )
  708. ret['static'] = 'extern'
  709. else:
  710. ret['callbackname'] = ret['name']
  711. ret['static'] = 'static'
  712. ret['argname'] = rout['name']
  713. ret['begintitle'] = gentitle(ret['name'])
  714. ret['endtitle'] = gentitle('end of %s' % ret['name'])
  715. ret['ctype'] = getctype(rout)
  716. ret['rctype'] = 'void'
  717. if ret['ctype'] == 'string':
  718. ret['rctype'] = 'void'
  719. else:
  720. ret['rctype'] = ret['ctype']
  721. if ret['rctype'] != 'void':
  722. if iscomplexfunction(rout):
  723. ret['returncptr'] = """
  724. #ifdef F2PY_CB_RETURNCOMPLEX
  725. return_value=
  726. #endif
  727. """
  728. else:
  729. ret['returncptr'] = 'return_value='
  730. if ret['ctype'] in cformat_map:
  731. ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
  732. if isstringfunction(rout):
  733. ret['strlength'] = getstrlength(rout)
  734. if isfunction(rout):
  735. if 'result' in rout:
  736. a = rout['result']
  737. else:
  738. a = rout['name']
  739. if hasnote(rout['vars'][a]):
  740. ret['note'] = rout['vars'][a]['note']
  741. rout['vars'][a]['note'] = ['See elsewhere.']
  742. ret['rname'] = a
  743. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, rout)
  744. if iscomplexfunction(rout):
  745. ret['rctype'] = """
  746. #ifdef F2PY_CB_RETURNCOMPLEX
  747. #ctype#
  748. #else
  749. void
  750. #endif
  751. """
  752. else:
  753. if hasnote(rout):
  754. ret['note'] = rout['note']
  755. rout['note'] = ['See elsewhere.']
  756. nofargs = 0
  757. nofoptargs = 0
  758. if 'args' in rout and 'vars' in rout:
  759. for a in rout['args']:
  760. var = rout['vars'][a]
  761. if l_or(isintent_in, isintent_inout)(var):
  762. nofargs = nofargs + 1
  763. if isoptional(var):
  764. nofoptargs = nofoptargs + 1
  765. ret['maxnofargs'] = repr(nofargs)
  766. ret['nofoptargs'] = repr(nofoptargs)
  767. if hasnote(rout) and isfunction(rout) and 'result' in rout:
  768. ret['routnote'] = rout['note']
  769. rout['note'] = ['See elsewhere.']
  770. return ret
  771. def common_sign2map(a, var): # obsolute
  772. ret = {'varname': a, 'ctype': getctype(var)}
  773. if isstringarray(var):
  774. ret['ctype'] = 'char'
  775. if ret['ctype'] in c2capi_map:
  776. ret['atype'] = c2capi_map[ret['ctype']]
  777. if ret['ctype'] in cformat_map:
  778. ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
  779. if isarray(var):
  780. ret = dictappend(ret, getarrdims(a, var))
  781. elif isstring(var):
  782. ret['size'] = getstrlength(var)
  783. ret['rank'] = '1'
  784. ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
  785. if hasnote(var):
  786. ret['note'] = var['note']
  787. var['note'] = ['See elsewhere.']
  788. # for strings this returns 0-rank but actually is 1-rank
  789. ret['arrdocstr'] = getarrdocsign(a, var)
  790. return ret